SQL Where Clause with exclusions - where-clause

Hello I have a code where I am excluding some Catastrophe codes however I realized I shouldn't filter them all only the ones with those codes and the cause of loss a.CauseOfLoss <> '170 - All Other Liability'. How can I update this where clause?
WHERE (
b.CatastropheCode <> '228' and
b.CatastropheCode <> '312' and
b.CatastropheCode <> '317' and
b.CatastropheCode <> '525' and
b.CatastropheCode <> '612' and
b.CatastropheCode <> '615' and
b.CatastropheCode <> '811' and
b.CatastropheCode <> '916' and
b.CatastropheCode <> '1012' and
b.CatastropheCode <> '1113' and
b.CatastropheCode <> 'MATT'
)

Related

I need help defining a case statement in SQL db2-400

I am using SQL, IBM Data Studio, db2-400. I need help writing a case statement that looks for the length of a field and returns a blank if it is not equal to 14, I have tried many ways without success, below is my latest attempt.
CASE
WHEN LENGTH(TRIM(FFIUPCN) <> '14'
THEN ''
ELSE
FFIUPCN
END AS "UPC (if applicable)"
The error I get is that the token "<>" is not valid.
Main issue is that you are missing a )
CASE
WHEN LENGTH(TRIM(FFIUPCN)) <> 14
THEN ''
ELSE
FFIUPCN
END AS "UPC (if applicable)"
but you shouldn't be comparing a numeric, returned by length(), to a sring '14'. But Db2 is implicitly converting it.
For multiple conditions you can nest your case statements
Select
case when FIUPCN+FFIUPCN2 = 0
then case when FIUPCN >= value then FIUPCN + 1
else FIUPCN + 2 end
else
case when FIUPCN >= value
then case when FIUPCN <> ''
then FIUPCN + 3
else prvca1 end
else
case
when FIUPCN >= FIUPCN2 and FIUPCN3 <> 0 then FIUPCN + 4
when FIUPCN >= FIUPCNX and FIUPCNY <> 0 then FIUPCN + 5
else prvca1 end
end
end
from table

Best performance for paging query when using multiple statements in sql?

It is a bit complicated query but let me elaborate,
i have got multiple filter parameters in my procedure,
also a view named Vw1 and its regarded my main object in query that most of the filter parameters are filtered against this view that is located in another server,then i need to compare this view to another table and check two sides columns for possible conflict and then check if there is any conflict.
you can see my query below
ALTER PROC [dbo].[spGetAyandehVagozariWithConflict]
#Take INT,
#Skip INT,
#FromVagozariDate NVARCHAR(10),
#ToVagozariDate NVARCHAR(10),
#OrderBankCode NVARCHAR(4)=null,
#OrderBrCode NVARCHAR(7)=null,
#BenefBrCode NVARCHAR(4)=null,
#FromAmount NVARCHAR(50)=null,
#ToAmount NVARCHAR(50)=null,
#CheqSerie NVARCHAR(50)=null,
#CheqSerial NVARCHAR(10)=null,
#CheqStatus NVARCHAR(4)=null,
#CreditorNationalCode VARCHAR(20)=NULL,
#CheqType NVARCHAR(4)=null,
#BenefAccn NVARCHAR(13)=null,
#FromMatDate NVARCHAR(10)=null,
#ToMatDate NVARCHAR(10)=null,
#FromTaeenVaziatDate NVARCHAR(10)=null,
#ToTaeenVaziatDate NVARCHAR(10)=NULL,
#HasConflict VARCHAR(4)=null,
#TotalCnt INT OUTPUT,
#SUM BIGINT OUTPUT
AS
BEGIN
DECLARE #Query NVARCHAR(MAX)=''
IF(NULLIF(#FromVagozariDate,'') IS null)
SET #FromVagozariDate='NULL'
IF(NULLIF(#ToVagozariDate,'') IS null)
SET #ToVagozariDate='NULL'
IF(NULLIF(#OrderBrCode,'') IS null)
SET #OrderBrCode='NULL'
IF(NULLIF(#OrderBankCode,'') IS null)
SET #OrderBankCode='NULL'
IF(NULLIF(#BenefBrCode,'') IS null)
SET #BenefBrCode='NULL'
IF(NULLIF(#FromAmount,'') IS null)
SET #FromAmount='NULL'
IF(NULLIF(#ToAmount,'') IS null)
SET #ToAmount='NULL'
IF(NULLIF(#CheqSerie,'') IS null)
SET #CheqSerie='NULL'
IF(NULLIF(#CheqSerial,'') IS null)
SET #CheqSerial='NULL'
IF(NULLIF(#CheqStatus,'') IS null)
SET #CheqStatus='NULL'
IF(NULLIF(#CheqType,'') IS null)
SET #CheqType='NULL'
IF(NULLIF(#BenefAccn,'') IS null)
SET #BenefAccn='NULL'
IF(NULLIF(#ToMatDate,'') IS null)
SET #ToMatDate='NULL'
IF(NULLIF(#FromMatDate,'') IS null)
SET #FromMatDate='NULL'
IF(NULLIF(#FromTaeenVaziatDate,'') IS null)
SET #FromTaeenVaziatDate='NULL'
IF(NULLIF(#ToTaeenVaziatDate,'') IS null)
SET #ToTaeenVaziatDate='NULL'
IF(NULLIF(#HasConflict,'') IS null)
SET #HasConflict='NULL'
IF(NULLIF(#CreditorNationalCode,'') IS null)
SET #CreditorNationalCode='NULL'
IF #FromVagozariDate<>'NULL'
BEGIN
SET #FromVagozariDate=REPLACE(#FromVagozariDate,'/','')
END
IF #ToVagozariDate<>'NULL'
BEGIN
SET #ToVagozariDate=REPLACE(#ToVagozariDate,'/','')
END
IF #FromMatDate<>'NULL'
BEGIN
SET #FromMatDate=REPLACE(#FromMatDate,'/','')
END
IF #ToMatDate<>'NULL'
BEGIN
SET #ToMatDate=REPLACE(#ToMatDate,'/','')
END
IF #FromTaeenVaziatDate<>'NULL'
BEGIN
SET #FromTaeenVaziatDate=REPLACE(#FromTaeenVaziatDate,'/','')
SET #FromTaeenVaziatDate=SUBSTRING(#FromTaeenVaziatDate,3,6)
END
IF #ToTaeenVaziatDate<>'NULL'
BEGIN
SET #ToTaeenVaziatDate=REPLACE(#ToTaeenVaziatDate,'/','')
SET #ToTaeenVaziatDate=SUBSTRING(#ToTaeenVaziatDate,3,6)
END
IF #OrderBankCode<>'NULL'
BEGIN
--SET #OrderBankCode='0'+#OrderBankCode;
SET #OrderBankCode=dbo.LeftPad(#OrderBankCode,'0',3)
END
IF(#BenefBrCode<>'NULL')
BEGIN
SET #BenefBrCode=dbo.LeftPad(#BenefBrCode,'0',4)
END
IF(#OrderBrCode<>'NULL')
BEGIN
SET #OrderBrCode=dbo.LeftPad(#OrderBrCode,'0',4)
END
SET #Query=#Query+N'
SELECT *
INTO #Vw1
FROM [LinkedServer].DbName.dbo.Vw1 vd
where (vd.mat_date BETWEEN '+''''+#FromMatDate+''''+' AND'+''''+ #ToMatDate+''''+' OR ('+''''+#FromMatDate+''''+' =''NULL'' AND '+''''+#ToMatDate+''''+' =''NULL'' )) AND
(dbo.LeftPad(vd.order_bank_code,''0'',3)= '+''''+#OrderBankCode+''''+' OR '+''''+#OrderBankCode+''''+' =''NULL'') AND
(dbo.LeftPad(vd.order_brcode,''0'',4)= '+''''+#OrderBrCode+''''+' OR '+''''+#OrderBrCode+''''+' =''NULL'') AND
(dbo.LeftPad(vd.Benef_br_code,''0'',4)= '+''''+#BenefBrCode+''''+' OR '+''''+#BenefBrCode+''''+' =''NULL'') AND
(substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10) BETWEEN '+''''+#FromAmount+''''+' AND '+''''+#ToAmount+''''+' OR ('+''''+#FromAmount+''''+' =''NULL'' AND '+''''+#ToAmount+''''+' =''NULL'')) AND
(RTRIM(LTRIM(vd.chq_serie))= '+''''+#CheqSerie+''''+' OR '+''''+#CheqSerie+''''+' =''NULL'') AND
(RTRIM(LTRIM(vd.chq_serial))= '+''''+#CheqSerial+''''+' OR '+''''+#CheqSerial+''''+' =''NULL'') AND
(vd.Chq_stat= '+''''+#CheqStatus+''''+' OR '+''''+#CheqStatus+''''+' in (''NULL'',''-1'')) AND
(vd.chq_type= '+''''+#CheqType+''''+' OR '+''''+#CheqType+''''+' =''NULL'') AND
(vd.benef_acno= '+''''+#BenefAccn+''''+' OR '+''''+#BenefAccn+''''+' =''NULL'') AND
((vd.taeen_vaziat_date is null AND ('+''''+#CheqStatus+''''+'=''-1'')) or('+''''+#CheqStatus+''''+'<>''-1'') ) AND
(vd.vagozari_date BETWEEN '+''''+#FromVagozariDate+''''+' AND '+''''+#ToVagozariDate+''''+' OR ('+''''+#FromVagozariDate+''''+' =''NULL'' AND '+''''+#ToVagozariDate+''''+' =''NULL'')) AND
(vd.taeen_vaziat_date BETWEEN '+''''+#FromTaeenVaziatDate+''''+' AND '+''''+#ToTaeenVaziatDate+''''+' OR ('+''''+#ToTaeenVaziatDate+''''+' =''NULL'' AND '+''''+#FromTaeenVaziatDate+''''+' =''NULL''))
order by system_no
select distinct cast(benef_acno as bigint) benef_acno
into #acno
from #Vw1
select ACNO,CUSTNO
into #ACTINFO
from [LinkServer1].[Db1].[dbo].[ACTINFO] af
where accno_id in (select * from #acno)
select [ECONOMIC-CODE],CUSTNO,FIRSTNAME +'' ''+LASTNAME CUSTNAME
into #CUSTINFO
from [LinkServer1].[Db1].[dbo].[CUSTINFO]
where CustNo_Id in (select cast(CUSTNO as bigint) from #ACTINFO)
SELECT
vd.*,
ct.Title CheqTypeTitle,
af.CUSTNO,cf.CUSTNAME,
--'''' as CUSTNO,'''' CUSTNAME,
cs.Status CheqStatusTitle,
av.Id AyandehVagozariId,
p.ParticipantName BenefBankName,
CASE WHEN ISNULL(vd.vagozari_date,'''') <> COALESCE(REPLACE(av.VagozariDate,''/'',''''),vd.vagozari_date,'''') THEN 1 ELSE 0 END VagozariDateHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.order_bank_code,''0'',3),'''') <> COALESCE(av.Order_Bank_Code,dbo.LeftPad(vd.order_bank_code,''0'',3),'''') THEN 1 ELSE 0 END OrderBankCodeHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.order_brcode,''0'',4),'''') <> COALESCE(av.Order_brCode,dbo.LeftPad(vd.order_brcode,''0'',4),'''') THEN 1 ELSE 0 END OrderBrCodeHasConflict,
CASE WHEN ISNULL(dbo.LeftPad(vd.Benef_br_code,''0'',4),'''') <> COALESCE(av.Benef_Br_Code,dbo.LeftPad(vd.Benef_br_code,''0'',4),'''') THEN 1 ELSE 0 END BenefBrCodeHasConflict,
CASE WHEN ISNULL(substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10),'''') <> COALESCE(av.Amount,substring(vd.amount, patindex(''%[^0]%'',vd.amount), 10),'''') THEN 1 ELSE 0 END AmountHasConflict,
CASE WHEN ISNULL(vd.chq_serie,'''') <> COALESCE(av.Chq_serie,vd.chq_serie,'''') THEN 1 ELSE 0 END CheqSerieHasConflict,
CASE WHEN ISNULL(RTRIM(LTRIM(vd.chq_serial)),'''') <> COALESCE(av.Chq_Serial,RTRIM(LTRIM(vd.chq_serial)),'''') THEN 1 ELSE 0 END CheqSerialHasConflict,
CASE WHEN ISNULL(vd.chq_type,'''') <> COALESCE(av.Chq_Type,vd.chq_type,'''') THEN 1 ELSE 0 END CheqTypeHasConflict,
CASE WHEN ISNULL(vd.benef_acno,'''') <> COALESCE(av.Benef_Acno,vd.benef_acno,'''') THEN 1 ELSE 0 END BenefAcnoHasConflict,
CASE WHEN ISNULL(vd.mat_date,'''') <> COALESCE(REPLACE(av.Mat_Date,''/'',''''),vd.mat_date,'''') THEN 1 ELSE 0 END MatDateHasConflict,
CASE WHEN ISNULL(cf.CUSTNO,'''') <> COALESCE(av.CUSTNO,cf.CUSTNO COLLATE DATABASE_DEFAULT,'''') THEN 1 ELSE 0 END CustNoHasConflict,
--CASE WHEN ISNULL(vd.taeen_vaziat_date,'''') <> COALESCE(av.Taeen_Vaziat_Date,vd.taeen_vaziat_date,'''') THEN 1 ELSE 0 END TaeenVaziatDateHasConflict,
0 as TaeenVaziatDateHasConflict,
CASE WHEN ISNULL(vd.Chq_stat,'''') <> COALESCE(av.Chq_Status,vd.Chq_stat,'''') THEN 1 ELSE 0 END CheqStatusHasConflict
--0 as VagozariDateHasConflict,
--0 as OrderBankCodeHasConflict,
--0 as OrderBrCodeHasConflict,
--0 as BenefBrCodeHasConflict,
--0 as AmountHasConflict,
--0 as CheqSerieHasConflict,
--0 as CheqSerialHasConflict,
--0 as CheqTypeHasConflict,
--0 as BenefAcnoHasConflict,
--0 as MatDateHasConflict,
--0 as TaeenVaziatDateHasConflict
INTO #temp
FROM #vw_faranam_vagozari_chakavak vd
LEFT JOIN #ACTINFO af on vd.benef_acno=af.ACNO COLLATE Arabic_CI_AS
LEFT JOIN #CUSTINFO cf on af.CUSTNO=cf.CUSTNO COLLATE Arabic_CI_AS
LEFT JOIN [AyandehVagozari] av ON av.SystemNo=vd.system_no
LEFT JOIN [Cheque_Type_Biha] ct ON ct.Code=vd.chq_type
LEFT JOIN [ChequeStatusForBiha] cs ON cs.Id=vd.Chq_stat
LEFT JOIN [Participant] p ON ''0''+p.ParticipantCode=vd.order_bank_code
WHERE (cf.[ECONOMIC-CODE]= '+''''+#CreditorNationalCode+''''+' OR '+''''+#CreditorNationalCode+''''+' =''NULL'')
order by vd.system_no
DELETE t FROM(
SELECT *,ROW_NUMBER() OVER(partition by system_no order by AyandehVagozariId desc) rn FROM
#temp
)t
where rn>1
SELECT *,
case when (VagozariDateHasConflict=1 or OrderBankCodeHasConflict=1 or OrderBrCodeHasConflict =1 OR BenefBrCodeHasConflict=1
or AmountHasConflict=1 or CheqSerieHasConflict=1 or CheqSerialHasConflict=1 or CustNoHasConflict=1
or CheqStatusHasConflict=1 or CheqTypeHasConflict=1 or BenefAcnoHasConflict=1 or MatDateHasConflict=1 or TaeenVaziatDateHasConflict=1)
then 1 else 0 end HasConflict
INTO #TmpResult
FROM #temp
order by system_no
--here is where i filter my last parameter but it seems too late..because alot of records already involved !
SELECT *,ROW_NUMBER() over (ORDER BY system_no) RowNumber
into #finalTemp
FROM
#TmpResult
where (HasConflict=1 and '+''''+#HasConflict+''''+'=''1'')
OR (HasConflict=0 and '+''''+#HasConflict+''''+'=''0'')
OR ('+''''+#HasConflict+''''+'=''NULL'')
order by system_no
SELECT #Total=##ROWCOUNT
select #Sum=isnull(SUM(cast(amount as bigint)),0) from
#finalTemp
select * from
#finalTemp
WHERE RowNumber >'+CAST(#Skip AS NVARCHAR(10))+' AND RowNumber<=('+CAST(#Skip+#Take AS NVARCHAR(10))+')
'
PRINT #Query
EXEC sp_executesql #Query,N'#Total int output,#Sum bigint output',#TotalCnt OUTPUT,#SUM OUTPUT
END
due to performance issues i had to write it in dynamic way,But the problem is that i could not wrap my head around paging in this query, bacause as you see i should put paging line in the end of query because #HasConflict parameters exist and i cannot check it earlier,and in this way my paging seems pointless because i'm dealing with huge load of data ...
also i cannot use offset for paging because my sql version is too old ...

sql case statement in where clause , need to join check on different tables on different cases

SELECT
nc.status
FROM
newcustomer nc
INNER JOIN
#salesexec UserFiltr ON UserFiltr.userid = nc.reportedby
LEFT JOIN
distributor d ON nc.distributorid = d.distributorid
LEFT JOIN
shop s ON S.shopid = Nc.shopid
LEFT JOIN
shoptype st ON st.shoptypeid = s.shoptypeid
LEFT JOIN
#orgshop Orgfiltr ON Orgfiltr.organizationid = D.organizationid
WHERE
CONVERT(VARCHAR, nc.mobiletransactiondate, 101) BETWEEN #FromDate AND #ToDate
AND
CASE nc.status
WHEN 1
THEN (st.shoptype IS NULL OR st.shoptype = '' OR st.shoptype <> 'DISTRIBUTOR')
ELSE (nc.shoptype IS NULL OR nc.shoptype = '' OR nc.shoptype <> 'DISTRIBUTOR')
END
GROUP BY
reportedby
You may looking for this
AND
1 = CASE WHEN nc.status = 1 AND (st.shoptype IS NULL OR st.shoptype ='' OR st.shoptype <> 'DISTRIBUTOR' )
THEN 1
WHEN (nc.shoptype IS NULL OR nc.shoptype ='' OR nc.shoptype<> 'DISTRIBUTOR' )
THEN 1
END
I think I can see what you're trying to do.
I would use something like this:
WHERE CASE nc.STATUS
WHEN 1 THEN st.shoptype
ELSE nc.shoptype
END IS NULL
OR
CASE nc.STATUS
WHEN 1 THEN st.shoptype
ELSE nc.shoptype
END = ''
OR
CASE nc.STATUS
WHEN 1 THEN st.shoptype
ELSE nc.shoptype
END <> 'DISTRIBUTOR'
You sintax for case is wrong could be that you wnat check
( st.shoptype IS NULL
OR st.shoptype =''
OR st.shoptype<> 'DISTRIBUTOR' )
for assign a value eg:
CASE nc.status
WHEN (st.shoptype IS NULL
OR st.shoptype =''
OR st.shoptype<> 'DISTRIBUTOR' ) THEN 1
WHEN (nc.shoptype IS NULL
OR nc.shoptype =''
OR nc.shoptype<> 'DISTRIBUTOR' ) THEN 2
ELSE 3
END
Not clear what you need by you may try
WHERE
CONVERT(VARCHAR, nc.mobiletransactiondate, 101) BETWEEN #FromDate AND #ToDate
AND (
(nc.status=1 and (st.shoptype IS NULL
OR st.shoptype =''
OR st.shoptype<> 'DISTRIBUTOR' )
) OR
(nc.shoptype IS NULL
OR nc.shoptype =''
OR nc.shoptype<> 'DISTRIBUTOR' )
)

SQL query causing error due to group by statement (INVALID COLUMNS)

I have following SQL:
DECLARE #EmpId AS Varchar(20),
#CompanyId as VARCHAR(20),
#DepartmentId AS VARCHAR(20),
#DesignationId AS VARCHAR(20),
#GradeId AS VARCHAR(20),
#FromDate AS DATE,
#TillDate AS DATE
SET #EmpId = null
SET #CompanyId = NULL
SET #DepartmentId = NULL
SET #DesignationId = NULL
SET #GradeId = NULL
SET #FromDate = '1-1-2015'
SET #TillDate = '1-1-2016'
SELECT
LA.EmpId,AT.IsPaid AS 'IsPaid',
AT.AttendanceTypeCode,
(SELECT DISTINCT IsPaid
FROM LeaveApproval
WHERE empid = LA.EmpId) AS 'testPAID',
SUM(CASE WHEN AT.IsPaid = 1 THEN 1 END) AS Paid,
COUNT(CASE WHEN AT.IsPaid = 0 THEN AT.AttendanceTypeCode END) AS UnPaid,
COUNT(AT.AttendanceTypeCode) AS LeaveCount
FROM
LeaveApproval LA
INNER JOIN
AttendanceTypes AT ON LA.AttendanceTypeId = AT.AttendanceTypeId
INNER JOIN
EmpMaster EM ON LA.Empid = EM.EmpId
WHERE
EM.ActiveInActive <> 1 AND
EM.EmpId = CASE WHEN ISNULL(#EmpId ,'-1') <> '-1' AND #EmpId <> ''
THEN #EmpId
ELSE EM.EmpId
END
AND EM.CompanyId = CASE WHEN ISNULL(#CompanyId ,'-1') <> '-1' AND #CompanyId <> ''
THEN #CompanyId
ELSE EM.CompanyId
END
AND EM.DepartmentId = CASE WHEN ISNULL(#DepartmentId,'-1') <> '-1' AND #DepartmentId<> ''
THEN #DepartmentId
ELSE EM.DepartmentId
END
AND ISNULL(EM.DesignationId, '') = CASE WHEN ISNULL(#DesignationId ,'-1') <> '-1' AND #DesignationId <> '' THEN #DesignationId ELSE ISNULL(EM .DesignationId,'') END
AND ISNULL(EM.GradeId,'') = CASE WHEN ISNULL(#GradeId ,'-1') <> '-1' AND #GradeId <> '' THEN #GradeId ELSE ISNULL(EM .GradeId,'') END
AND FromDate BETWEEN #FromDate AND #TillDate
GROUP BY
LA.EmpID, AT.AttendanceTypeCode, AT.IsPaid, Paid, UnPaid
The above SQL is not working.
I get an error
Column Paid and InPaid are invalid.
What I know is that 'Paid' and Unpaid are from subquery and are NOT available in select list's group by.
My question is how can I achieve the above outcome after running my SQL my outcome should repeat same value which is sum for Paid for each empid
Any help will be appreciated
You cannot use an alias of a column of the current SELECT in its GROUP BY. You have to either do this:
Group By LA.EmpID,AT.AttendanceTypeCode,AT.IsPaid,SUM(CASE WHEN AT.IsPaid=1 Then 1 END), COUNT(CASE WHEN AT.IsPaid=0 Then AT.AttendanceTypeCode END)
Or use all your SELECT as a subquery and group by as you planned in the outer query.
DECLARE #EmpId AS Varchar(20),
#CompanyId as VARCHAR(20),
#DepartmentId AS VARCHAR(20),
#DesignationId AS VARCHAR(20),
#GradeId AS VARCHAR(20),
#FromDate AS DATE,
#TillDate AS DATE
Set #EmpId=null
SET #CompanyId= NULL
SET #DepartmentId=NULL
SET #DesignationId=NULL
SET #GradeId=NULL
SET #FromDate='1-1-2015'
SET #TillDate='1-1-2016';
with LeaveApprovalCTE as
(
Select
AT.IsPaid as 'IsPaid',
AT.AttendanceTypeCode, (select distinct IsPaid from LeaveApproval where empid=LA.EmpId) as 'testPAID',
CASE WHEN AT.IsPaid=1 Then 1 END as Paid,
CASE WHEN AT.IsPaid=0 Then AT.AttendanceTypeCode END as UnPaid,
AT.AttendanceTypeCode AS LeaveCount
From
LeaveApproval LA
INNER JOIN AttendanceTypes AT ON LA.AttendanceTypeId = AT.AttendanceTypeId
INNER JOIN EmpMaster EM ON LA.Empid = EM.EmpId
WHERE
EM.ActiveInActive <> 1 AND
EM.EmpId = CASE WHEN ISNULL(#EmpId ,'-1') <> '-1' AND #EmpId <> '' THEN #EmpId ELSE EM .EmpId END
AND
EM.CompanyId = CASE WHEN ISNULL(#CompanyId ,'-1') <> '-1' AND #CompanyId <> '' THEN #CompanyId ELSE EM .CompanyId END
AND
EM.DepartmentId = CASE WHEN ISNULL(#DepartmentId,'-1') <> '-1' AND #DepartmentId<> '' THEN #DepartmentId ELSE EM .DepartmentId END
AND
ISNULL(EM.DesignationId,'') = CASE WHEN ISNULL(#DesignationId ,'-1') <> '-1' AND #DesignationId <> '' THEN #DesignationId ELSE ISNULL(EM .DesignationId,'') END
AND
ISNULL(EM.GradeId,'') = CASE WHEN ISNULL(#GradeId ,'-1') <> '-1' AND #GradeId <> '' THEN #GradeId ELSE ISNULL(EM .GradeId,'') END
AND
FromDate BETWEEN #FromDate AND #TillDate
)
Select
AttendanceTypeCode,
SUM(Paid) as paid ,
COUNT(UnPaid) as unpaid,
COUNT(LeaveCount) AS LeaveCount
from LeaveApprovalCTE
Group By AttendanceTypeCode,IsPaid,Paid,UnPaid
Use CTE for add new columns in query . Modify your query like this . hope it will work for you

SQL SubQuery Error

I would like to retrieve the data in the following sample.The following SQL will return two records.
SELECT -1 AS NUM
FROM TABLE
WHERE COMP_CODE = 'TEST'
AND (DETL_REMK = 'Rest Day'
OR SHFT_CODE = 'WK_PH')
AND RSRV_DATE_1 IS NOT NULL
AND RSRV_DATE_1 BETWEEN #TR_FR AND #TR_TO
AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID,
RSRV_DATE_1
I would like to show the below.
ORG UNIT EMPE_ID FAM_NAME TMS_TYPE Qty
-----------------------------------------------------------------
'' '' '' Used -1
'' '' '' Used -1
So, I 'm trying to do like that the SQL statement. But I got the error
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
How to construct the right SQL. Please help me. Thanks in advance.
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE,
ISNULL(CAST(
(SELECT -1 AS NUM
FROM TABLE
WHERE COMP_CODE = 'TEST'
AND (DETL_REMK = 'Rest Day'
OR SHFT_CODE = 'WK_PH')
AND RSRV_DATE_1 IS NOT NULL
AND RSRV_DATE_1 BETWEEN #TR_FR AND #TR_TO
AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID, RSRV_DATE_1)AS NVARCHAR(MAX)),0) QTY
If you're just hardcoding the values outside the subquery, you don't need a subquery to return the 2 rows, just do this:
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 AS QTY
FROM TABLE
WHERE COMP_CODE = 'TEST'
AND (DETL_REMK = 'Rest Day'
OR SHFT_CODE = 'WK_PH')
AND RSRV_DATE_1 IS NOT NULL
AND RSRV_DATE_1 BETWEEN #TR_FR AND #TR_TO
AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID,
RSRV_DATE_1
The issue here is you're not referencing any columns from your table, just using it to produce an amount of rows. Please share the full issue and code, as I'm sure there is more to this that what you're asking.
You can try this one instead
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY
union all
SELECT '' ORG_UNIT, '' EMPE_ID, '' FAM_NAME, 'Used' AS TMS_TYPE, -1 as QTY
You would need to add Top 1 to your subquery, from the error you are getting, looks like the subquery is returning more than 1 row:
SELECT Top 1 -1 AS NUM
FROM TABLE
WHERE COMP_CODE = 'TEST'
AND (DETL_REMK = 'Rest Day',
OR SHFT_CODE = 'WK_PH')
AND RSRV_DATE_1 IS NOT NULL
AND RSRV_DATE_1 BETWEEN #TR_FR AND #TR_TO
AND EMPE_ID = 'TEST'
GROUP BY EMPE_ID, RSRV_DATE_1