Using an OnCalcField with a query - mysql

// accounts receivable
qAR.SQL.Clear;
qAR.SQL.Text := 'Select C.Lastname,C.Firstname,C.Address,C.City,C.State,C.Zip,' +
'C.Hercell,C.Hiscell,C.Phone,C.Code,' +
'I.Date,I.Clino,I.Date,I.ToBePaid,' +
'SUM(CASE when C.Clino = I.Clino then I.ToBePaid END) as nToBePaid,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S0 and :E0 then I.ToBePaid END) as nCurrent,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S1 and :E1 then I.ToBePaid END) as nOver30,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S2 and :E2 then I.ToBePaid END) as nOver60,' +
'SUM(CASE when C.Clino = I.Clino and I.Date <= :E3 then I.ToBePaid END) as nOver90 ' +
'from Invoice I ' +
'join Client C on C.Clino = I.Clino ' +
'where I.Date <= :E ' +
'and I.ToBePaid <> 0 ' +
'and I.Active = true ' +
'and C.Code <> 1 ' +
'group by C.Clino ' +
'having nToBePaid > 0 ' +
'order by C.Lastname,C.Firstname';
qAR.ParamByName('S0').AsDate := dDate30 + 1;
qAR.ParamByName('E0').AsDate := dBillingDate;
qAR.ParamByName('S1').AsDate := dDate60 + 1;
qAR.ParamByName('E1').AsDate := dDate30;
qAR.ParamByName('S2').AsDate := dDate90 + 1;
qAR.ParamByName('E2').AsDate := dDate60;
qAR.ParamByName('E3').AsDate := dDate90;
qAR.ParamByName('E').AsDate := dBillingDate;
qAR.FieldDefs.Updated := false;
qAR.FieldDefs.Update;
oField := TBooleanField.Create( qAR );
oField.FieldKind := fkCalculated;
qAR.OnCalcFields := qARCalcFields;
qAR.DetailFields := 'Clino';
qAR.Open;
I have a calculated field Sel (boolean) define in this query. I want to click a button and have the Sel fields on all records to be set to TRUE and another button and have them all set to FALSE. What should the code of 1) the OnCalcField and 2) each of the buttons be?
Thanks,
Jim Sawyer

Related

MySQL Procedure error in server

I am getting this following error , the same code is not throwing any error in my local system.
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'GROUP_CONCAT(CASE WHEN atv.alid = 1906962 and atv.atrtid = 1
THEN concat(replac' at line 1
below i posted my code
BEGIN
SET
##group_concat_max_len = 1024 * 13;
SET
#sql3 = NULL;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END),2), ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format( SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2), ", ","") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql1
FROM
business_tax_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butaptid = 2 AND b.butapsid = 1 AND b.company_id = 19;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END) , 2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format(SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql4
FROM
business_tax_sub_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butasuptid = 2 AND b.company_id = 19 AND b.butasupsid = 1;
SELECT
GROUP_CONCAT(
CONCAT(
'GROUP_CONCAT(CASE WHEN atv.alid = ',
c.alid,
' and atv.atrtid = 1 THEN concat(replace(format(atv.amount,2),", ","") , "") when atv.alid=',
c.alid,
' AND atv.atrtid = 2 then concat(replace(format(atv.amount , 2),", ","") , "") END) as `',
TRIM(ao.name),
'`'
)
)
INTO
#sql2
FROM
extra_charges c
LEFT JOIN
account_ledger ao ON(
ao.alid = c.alid AND ao.company_id = 19
)
WHERE
c.ectid = 2 AND c.company_id = 19 AND c.ecsid = 1;
SET
#sql3 = CONCAT(
'CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = root#localhost SQL SECURITY DEFINER VIEW `purchase_invoice_tax_report_view_19` AS SELECT i.pinvid as pinvid, ROUND(i.total_tax_amount,2) AS `total_tax_amount1`, i.outlet_chkid,i.receive_date as receive_date, i.total_qty, replace(format(i.payable_amount,2),", ","") as payable_amount, replace(format((i.complete_amount -i.total_tax_amount),2) , ", " , "") as total_amount_before_tax, v.gstin, v.data as vendor_data, group_concat((case when atv.alid = 35 and atv.atrtid = 1 then concat(replace(format(atv.amount,2),", ","") , "") when atv.alid = 35 and atv.atrtid = 2 then concat(replace(format(atv.amount,2),", ",""), "") end) separator " ") as `round`,',
COALESCE(#sql1,
'"0"'),
',',
COALESCE(#sql4,
'"0"'),
',',
COALESCE(#sql2,
'"0"'),
', al.name as vendor_name , i.date, (CASE WHEN i.is_transportation IS NULL and is_expense = 0 THEN "Purchase" WHEN i.is_transportation IS NULL and is_expense > 0 THEN "Expense" WHEN i.is_transportation > 0 and is_expense >0 THEN "Transportation" ELSE "Purchase" END) as purchase_type,i.invoice_number ,(case when a.avtid = 3 then "Purchases" end) as voucher_type , a.avtid, i.pinvsid FROM purchase_invoice i LEFT JOIN account_transaction atv ON(atv.avid = i.avid and atv.company_id = 19) left join account_voucher a on (a.avid = atv.avid and a.company_id=19) LEFT join vendor v on (v.venid = i.venid and v.company_id = 19) LEFT join account_ledger al on(al.alid = v.alid and al.company_id = 19) where a.avsid = 1 and a.avtid = 3 and a.company_id = 19 group by i.pinvid'
);
PREPARE
stmt
FROM
#sql3;
EXECUTE
stmt;
DEALLOCATE
PREPARE
stmt;
END
is there any syntax error or anything else because the same code working fine in the local system ....

mysql average of best three

I have pieced this together from sites online and it works but not completely, what i need it to do is take the top 3 results and average them but it takes ALL results, can anyone point me in the right direction?
SELECT i.NAME,
e.comp,
Round(Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6), 2) AS "Average Score",
( CASE
WHEN compID = '7' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 400 ) * 100), 2), ' %')
WHEN compID = '5' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
WHEN compID = '3' THEN
Concat(Round(Avg(( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
ELSE 'Unspecified'
END ) AS "Average as Percent"
FROM jos_practicedetail c,
jos_comps e,
jos_practice g,
jos_members i
WHERE e.compsid = g.competition
AND g.practiceid = c.practicepid
AND i.memberid = c.competitorid
AND g.typeID = '2'
AND Year(g.pdate) = '2017'
AND (SELECT Count(*)
FROM jos_practicedetail b
WHERE b.competitorid = c.competitorid
AND b.practicepid = c.practicepid
AND ( b.phase1 + b.phase2 + b.phase3 + b.phase4 + b.phase5
+ b.phase6 ) >= (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 )) <= 3
GROUP BY competitorid
HAVING Count(*) > 2
ORDER BY competitorid,
( Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6) ) DESC

Send sql email from two select results

I need help, I want to ask, I send emails in two SQL tables as a body of the email. However, when the first table has no results, sends a blank email to me, even though the results of the second table exists.
The problem is with #body = #html1
Thank you very much
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum2]'))
DROP VIEW [dbo].[qdatum2]
GO
-- vytvorenie
CREATE VIEW qdatum2 AS
SELECT(A.Firma) AS FIRMA, A.ID, (A.OBEC) AS OBEC, (A.Ulice) AS Ulica, A.Obec2 as 'Obec dod.', A.Ulice2 AS 'Ulica dod.',
VP.IDS AS REGION,
CAST(SUM(CASE WHEN F.RelTpFak = 2 THEN -F.Kc2 ELSE F.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(F.DATUM) AS MAXDATUM, MIN(F.DATUM) AS MINDATUM
FROM (StwPh_35760532_2015.dbo.AD as A INNER JOIN StwPh_35760532_2015.dbo.sVPULpol AS VP ON A.RefVPrRegion = VP.ID)
inner JOIN StwPh_35760532_2015.dbo.FA AS F ON A.ID = F.RefAD
WHERE DATEADD(MONTH, 6, F.Datum) > GETDATE()
GROUP BY A.ID, a.Firma, A.Obec, A.Ulice, A.Obec2, A.Ulice2, VP.IDS
union all
SELECT(AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.',
sVPULpol.IDS AS REGION,
CAST(SUM(CASE WHEN FA.RelTpFak = 2 THEN -FA.Kc2 ELSE FA.Kc2 END) AS DECIMAL(36,2)) AS OBRAT, MAX(FA.DATUM) AS MAXDATUM, MIN(FA.DATUM) AS MINDATUM
FROM (AD INNER JOIN sVPULpol ON AD.RefVPrRegion = sVPULpol.ID) inner JOIN FA ON AD.ID = FA.RefAD
WHERE DATEADD(MONTH, 6, FA.Datum) > GETDATE()
GROUP BY AD.ID, ad.Firma, ad.Obec, ad.Ulice,AD.Obec2,AD.Ulice2, sVPULpol.IDS
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum1]'))
DROP VIEW [dbo].[qdatum1]
GO
-- vytvorenie
CREATE VIEW qdatum1 AS
select (AD.Firma) AS FIRMA, AD.ID, (AD.OBEC) AS OBEC, (AD.Ulice) AS Ulica, AD.Obec2 as 'Obec dod.', AD.Ulice2 AS 'Ulica dod.', qdatum2.REGION,
SUM(qdatum2.OBRAT) as OBRAT, max(qdatum2.MAXDATUM) as MAXDATUM, MIN(qdatum2.MINDATUM) AS MINDATUM
from AD INNER JOIN qdatum2 ON AD.ID = qdatum2.ID
group by ad.id, ad.Firma, ad.Obec, ad.Ulice, ad.Obec2, ad.Ulice2, qdatum2.region
go
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[qdatum]'))
DROP VIEW [dbo].[qdatum]
GO
-- vytvorenie
CREATE VIEW qdatum AS
SELECT qDATUM1.*
FROM qdatum1
WHERE DATEADD(DAY, 30, qdatum1.MAXDATUM) < getdate()
and qdatum1.REGION like '%OR%'
and qdatum1.OBRAT > 50
GO
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX))
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
Try using this:
DECLARE #html varchar(max)
SET #html = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD AKTIVNYCH ZAKAZNIKOV BEZ ODBERU ZA POSLEDNYCH 30 DNI </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Obrat v € za posledných 6 mesiacov</th><th>Posledna. Faktura</th>
</tr>' +
ISNULL(CAST (( SELECT
td = qdatum.FIRMA, ' ',
td = qdatum.OBEC, ' ',
td = CASE WHEN qdatum.Ulica IS NULL THEN '''' ELSE qdatum.Ulica END, ' ',
td = CASE WHEN qdatum.[Obec dod.] IS NULL THEN '''' ELSE qdatum.[Obec dod.] end , ' ',
td = CASE WHEN qdatum.[Ulica dod.] IS NULL THEN '''' ELSE qdatum.[Ulica dod.] END, ' ',
td = qdatum.OBRAT, ' ',
td = CONVERT(VARCHAR(11),qdatum.MAXDATUM, 106)
from StwPh_35760532_2016.dbo.qdatum
where qdatum.REGION like '%B1OR%'
order by qdatum.MAXDATUM
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)), '')
+
'<table>'
DECLARE #html1 varchar(max)
SET #html1 = '<html>'
+ '<H3><font id="Text" style="color: Green;">PREHLAD KOMUNIKÁCIE SO ZÁKAZNÍKOM REGION B1OR </H3>'
+ '<table border="1" bordercolor="#3300FF" style="background-color:#DDF8CC" width="70%" cellpadding=3 cellspacing=3>'
+ '<tr><font color="Green"><th>Firma</th><th>Obec</th><th>Ulica</th><th>Obec dod.</th><th>Ulica dod.</th><th>Posledna navsteva</th><th>Posledne volanie</th></tr>' +
ISNULL(CAST( (SELECT
td = AD.Firma , ' ',
td = AD.Obec, ' ',
td = CASE WHEN AD.Ulice IS NULL THEN '''' ELSE AD.Ulice END, ' ',
td = CASE WHEN AD.Obec2 IS NULL THEN '''' ELSE AD.Obec2 END, ' ',
td = CASE WHEN AD.Ulice2 IS NULL THEN '''' ELSE AD.Ulice2 END, ' ',
td = CASE WHEN CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR (11), AD.VPrnavsteva, 106) END, ' ',
td = CASE WHEN CONVERT(VARCHAR(11), AD.VPrvolane, 106) IS NULL THEN '''' ELSE CONVERT(VARCHAR(11), AD.VPrvolane, 106) END
FROM StwPh_35760532_2016.dbo.AD INNER JOIN StwPh_35760532_2016.dbo.sVPULpol ON AD.RefVPrRegion = sVPULpol.ID
WHERE AD.VPrnavsteva < DATEADD(DAY, -30 , GETDATE()) AND AD.VPrvolane < DATEADD(DAY, -30 , GETDATE())
AND AD.RefAD IS NULL
AND sVPULpol.IDS like '%B1OR%'
ORDER BY VPrnavsteva DESC
FOR XML PATH ('tr'),ELEMENTS
) AS VARCHAR(MAX)),'')
+
'</table>'
+ #html
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'LACI_ADMINISTRATOR',
--#recipients = 'emailxx',
#copy_recipients = 'emailxy',
--#blind_copy_recipients = 'emailxxy',
#subject ='B1OR report',
#body = #html1,
#body_format = 'HTML'
I added ISNULL on your CAST(SELECT) so that your variable will not turn to null if SELECT doesn't return data.

SQL Server order desc and also show 6/6

I have a 3 columns in a table named col1, col2, col3 containing integer values. there are 4000 + rows. there is three parameter #first, #second , #third. I want to get rows who has match according to this parameter. The query is giving results but it is not giving me 3/3 or if there is no match it is not showing and also I want to make it descending order.
My output should be like this
table :
col1 col2 col3
3 4 5
1 2 2
7 7 9
3 2 3
1 8 9
1 2 3
first = 1 second = 2 and third = 3
3 / 3 1 ( as sixth row contains 1, 2, 3)
2 / 3 2 ( as second row and fourth row )
1 / 3 1 (fifth row)
0 / 3 2 (ist , third )
(
SELECT count (CASE WHEN col1 = #First THEN 1 ELSE 0 END +
CASE WHEN col2= #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END
)AS "NUM_OF_MATCHES" ,
CAST( CASE WHEN col1 = #First THEN 1 ELSE 0 END +
CASE WHEN col2= #sec/ond THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END
AS VARCHAR(10)) + '/ 3'
AS "match"
FrOM dbo.FormsDataRowFormat a
where ( SELECT CASE WHEN col1 = #First THEN 1 ELSE 0 END +
CASE WHEN col2= #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END AS "NUM_OF_MATCHES" ) >= 1
group by ( CASE WHEN col1 = #First THEN 1 ELSE 0 END +
CASE WHEN col2 = #second THEN 1 ELSE 0 END+
CASE WHEN col3 = #third THEN 1 ELSE 0 END )
)
SELECT
'0/3' AS Matches,
SUM(CASE WHEN (CASE WHEN col1 = #first THEN 1 ELSE 0 END +
CASE WHEN col2 = #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END) = 0 THEN 1 ELSE 0 END) AS NumMatches
FROM FormsDataRowFormat
UNION
SELECT '1/3' AS Matches,
SUM(CASE WHEN (CASE WHEN col1 = #first THEN 1 ELSE 0 END +
CASE WHEN col2 = #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END) = 1 THEN 1 ELSE 0 END) AS NumMatches
FROM FormsDataRowFormat
UNION
SELECT '2/3' AS Matches,
SUM(CASE WHEN (CASE WHEN col1 = #first THEN 1 ELSE 0 END +
CASE WHEN col2 = #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END) = 2 THEN 1 ELSE 0 END) AS NumMatches
FROM FormsDataRowFormat
UNION
SELECT '3/3' AS Matches,
SUM(CASE WHEN (CASE WHEN col1 = #first THEN 1 ELSE 0 END +
CASE WHEN col2 = #second THEN 1 ELSE 0 END +
CASE WHEN col3 = #third THEN 1 ELSE 0 END) = 3 THEN 1 ELSE 0 END) AS NumMatches
FROM FormsDataRowFormat
For input data:
/--------------------\
| col1 | col2 | col3 |
|------+------+------|
| 8 | 7 | 1 |
| 5 | 7 | 1 |
| 4 | 4 | 4 |
| 4 | 5 | 2 |
| 4 | 6 | 2 |
| 2 | 2 | 3 |
| 5 | 2 | 1 |
| 2 | 7 | 7 |
| 2 | 1 | 3 |
| 1 | 2 | 3 |
\--------------------/
with:
#first = 1
#second = 2
#third = 3
gives output:
/----------------------\
| Matches | NumMatches |
|---------+------------|
| 0/3 | 6 |
| 1/3 | 2 |
| 2/3 | 1 |
| 3/3 | 1 |
\----------------------/
Edit - Dynamic SQL solution:
Following your comment clarifying that the number of columns is dynamic (between 3 and 6 inclusive), below is a dynamic SQL solution which will handle any such number of columns.
Note however that dynamic SQL is probably not the best solution to this problem, especially if it's something which will be repeated many times and/or runs on very large datasets. However, it's the only way I know to achieve this, so I wanted to include it (and would be very happy to see better solutions from other users!).
DECLARE #numColumns INT
SELECT #numColumns = COUNT(*) FROM sysobjects o JOIN syscolumns c ON o.id = c.id WHERE o.name = 'FormsDataRowFormat'
DECLARE #sql NVARCHAR(MAX)
SET #sql =
'SELECT ' +
'''0/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 0 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' +
'UNION ' +
'SELECT ''1/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 1 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' +
'UNION ' +
'SELECT ''2/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 2 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' +
'UNION ' +
'SELECT ''3/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 3 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' +
CASE WHEN #numColumns >= 4 THEN
'UNION ' +
'SELECT ''4/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 4 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN
'UNION ' +
'SELECT ''5/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 5 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat ' ELSE '' END +
CASE WHEN #numColumns = 6 THEN
'UNION ' +
'SELECT ''6/' + CONVERT(VARCHAR,#numColumns) + ''' AS Matches, ' +
'SUM(CASE WHEN (CASE WHEN col1 = ' + CONVERT(VARCHAR,#first) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col2 = ' + CONVERT(VARCHAR,#second) + ' THEN 1 ELSE 0 END + ' +
'CASE WHEN col3 = ' + CONVERT(VARCHAR,#third) + ' THEN 1 ELSE 0 END' +
CASE WHEN #numColumns >= 4 THEN ' + CASE WHEN col4 = ' + CONVERT(VARCHAR,#fourth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns >= 5 THEN ' + CASE WHEN col5 = ' + CONVERT(VARCHAR,#fifth) + ' THEN 1 ELSE 0 END' ELSE '' END +
CASE WHEN #numColumns = 6 THEN ' + CASE WHEN col6 = ' + CONVERT(VARCHAR,#sixth) + ' THEN 1 ELSE 0 END' ELSE '' END +
') = 6 THEN 1 ELSE 0 END) AS NumMatches ' +
'FROM FormsDataRowFormat' ELSE '' END
EXEC sp_executesql #sql

My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '8:45 AM' to data type int.
My Script is
Declare #SpecimenId bigint = 0, #script varchar(MAX);
Declare #StartTime int = (Select Convert(int,SUBString(START_TIME,0,CHARINDEX(':', START_TIME)) - 12) From APPT
Where APPT._ID=112601)
--select #StartTime
Set #script =
'SELECT distinct PTLAST_NAME + '', '' + PT.FIRST_NAME As PATIENT_NAME,
dbo.FormatDate(PT.DOB,''MM/dd/yyyy'') As DOB,
(Convert(varchar, (DATEDIFF(yy, DOB, APPT_DATE) - CASE WHEN (MONTH(DOB) > MONTH(APPT_DATE)) OR (MONTH(DOB) = MONTH(APPT_DATE) AND DAY(DOB) > DAY(APPT_DATE)) THEN 1 ELSE 0 END)) + ''/'' +
Convert(varchar, (DATEDIFF(m, DATEADD(yy, (DATEDIFF(yy, DOB, APPT_DATE) - CASE WHEN (MONTH(DOB) > MONTH(APPT_DATE)) OR (MONTH(DOB) = MONTH(APPT_DATE) AND DAY(DOB) > DAY(APPT_DATE)) THEN 1 ELSE 0 END), DOB), APPT_DATE) - CASE WHEN DAY(DOB) > DAY(APPT_DATE) THEN 1 ELSE 0 END)) + ''/'' +
Convert(varchar, (DATEDIFF(d, (DATEADD(m, (DATEDIFF(m, DATEADD(yy, (DATEDIFF(yy, DOB, APPT_DATE) - CASE WHEN (MONTH(DOB) > MONTH(APPT_DATE)) OR (MONTH(DOB) = MONTH(APPT_DATE) AND DAY(DOB) > DAY(APPT_DATE)) THEN 1 ELSE 0 END), DOB), APPT_DATE) - CASE WHEN DAY(DOB) > DAY(APPT_DATE) THEN 1 ELSE 0 END), (DATEADD(yy, (DATEDIFF(yy, DOB, APPT_DATE) - CASE WHEN (MONTH(DOB) > MONTH(APPT_DATE)) OR (MONTH(DOB) = MONTH(APPT_DATE) AND DAY(DOB) > DAY(APPT_DATE)) THEN 1 ELSE 0 END), DOB)))), APPT_DATE)))) As PatAge,
PT.Org_Id, PT.ADDRESS1 As PatAddress,
PT.LAST_NAME As LastName,PT.FIRST_NAME As FirstName,
PT.MIDDLE_NAME As MiddleName,
PHY.LAST_NAME + '', '' + PHY.FIRST_NAME As Physician,
dbo.FormatDate(APPT.APPT_DATE,''MM/dd/yyyy'') As CollectedDate,
(Case when SUBString(START_TIME,0,CHARINDEX('':'', START_TIME)) < 12 Then Convert(varchar,START_TIME) + Convert(varchar,'' AM'') ELSE' +Convert(varchar,#StartTime)+ '+ SUBString(START_TIME,3,6) + '' PM'' END) As CollectedTime,
(Case When PT.GENDER =''1'' Then ''M'' Else ''F'' End) As Gender,PT.CITY,LST.State_Short_Name As State ' +
(Case When #SpecimenId = 0 Then ', 0 As SpeciId' Else ', (Case When Tbl_Pat.Speci_Id > 0 Then Tbl_Pat.Speci_Id Else '''' End) As SpeciId' End) +
' FROM PT INNER JOIN
APPT ON PT.PAT_ID = APPT.PAT_ID INNER JOIN
PHY ON APPT.PHY_ID = PHY.PHY_ID INNER JOIN
LST ON PT.STATE = LST.STATE_ID ' +
(Case When #SpecimenId = 0 Then '' Else 'LEFT OUTER JOIN Tbl_Pat ON APPT.APPT_ID = Tbl_Pat.Speci_ApptId' End)
+ ' WHERE (APPT.APPT_ID = 112601) ' +
(Case When #SpecimenId = 0 Then '' Else 'AND (Tbl_Pat.Speci_Id = ' + Convert(varchar, #SpecimenId) + ')' End)
exec (#script)
Can Anyone help or correct my script please