How to use WHERE in an IF satement - tsql

I would like to do the following:
IF [Question ID] = 'Q1' AND [Textual Answer] = 'Satisfied'
THEN [Textual Answer] WHERE [Antwoord-ID] = [Antwoord-ID] AND [Question ID] = 'Q3' END
How can I include a WHERE in an IF statement?

The SQL syntax is CASE
SELECT
CASE
WHEN [Question ID] = 'Q1' AND [Textual Answer] = 'Satisfied' THEN [Textual Answer]
END
WHERE [Antwoord-ID] = [Antwoord-ID]
AND [Question ID] = 'Q3'
However, as #AhmedShefeer points out, this will always be NULL as you're trying expecting [Question ID] to 'Q1' and 'Q3' at the same time

Check the below code- You can use IIF() Function in SQL Server
SELECT
IIF( ([Question ID] = 'Q1' AND [Textual Answer] = 'Satisfied'), [Textual Answer] ,'') AS [Answer] --Give your else case instead of ''
WHERE [Antwoord-ID] = [Antwoord-ID]
AND [Question ID] = 'Q3';

Related

Optimise case/decode query in Postgres

Can anyone help me to implement the below query in another way? I am facing a performance issue because the same multiple SELECT statements are used everywhere in multiple CASE statements.
My code is very big, a chunk of it is here:
select col1,col2,
( CASE
WHEN NOT EXISTS (SELECT
CASE over.ola
WHEN NULL::text THEN 'NT'::character varying
END AS tover
FROM tsmt over
WHERE over.cod = hfprc.cod
AND over.vdat = nav.vdat) THEN 'NT'
ELSE (SELECT CASE over.ola
WHEN NULL::text THEN 'TT'::character varying END
FROM tsmt over
WHERE over.cod = hfprc.cod
AND over.vdat = nav.vdat)
END )
olaflag,
(SELECT description
FROM tolahfp tover
WHERE tover.ola = (SELECT CASE
WHEN NOT EXISTS (SELECT
CASE over.ola
WHEN NULL::text THEN 'TT'::character varying
END AS
tover
FROM tsmt over
WHERE over.cod = hfprc.cod
AND over.vdat = nav.vdat) THEN 'TT'
ELSE (SELECT CASE over.ola
WHEN NULL::text THEN 'TT'::character varying
END AS tover
FROM tsmt over
WHERE over.cod = hfprc.cod
AND over.vdat = nav.vdat)
END ola
))
ola,--ola description
(CASE thfp.codcag::text
WHEN NULL::text THEN 'CCCC'::character varying
END
)codcag,
(SELECT conf.descag
FROM thfconagrhfp conf
WHERE conf.codcag = CASE thfp.codcag::text
WHEN NULL::text THEN 'CCCC'::character varying
END)
desccag,
thfp.frq,
thfp.flgcal
FROM thpr hfprc LEFT JOIN tgrpprchfp grp ON hfprc.cgrp = grp.cgrp
LEFT JOIN tnav nav ON hfprc.cod = nav.cod AND nav.flag = 'Y'
LEFT JOIN thf thfp ON hfprc.cod = thfp.cod
LEFT JOIN tsmtdatthdhfp smtdatthd ON hfprc.cod = smtdatthd.cod
Do you use sqlsmith to write your queries?
But, more seriously, the way forward here is to replace subselects with outer joins.
As an example:
SELECT CASE WHEN NOT EXISTS (SELECT weirdfunc(x.x1)
FROM x
WHERE x.x2 = y.y2
AND x.x3 = z.z3)
THEN 'Constant'
ELSE (SELECT otherweirdfunc(x.x1)
FROM x
WHERE x.x2 = y.y2
AND x.x3 = z.z3)
END
FROM y
LEFT JOIN z USING (t);
would be better and more efficiently be written as
SELECT coalesce(otherweirdfunc(x.x1), 'Constant')
FROM y
LEFT JOIN z USING (t)
LEFT JOIN x ON x.x2 = y.y2 AND x.x3 = z.z3;
My rule of thumb is: subselects are usually wrong anywhere except in the FROM clause.

Using the TextHeader and TextBody property to define the view

I've been tasked to create a Powershell script that will create the following view which works currently within Microsoft SQL Studio. I've made a copy of the working script and would like to to apply it to this Microsoft example. My question is - can you take the known working query below and insert it in the TextBody property below?
# Set the TextHeader and TextBody property to define the view.
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
$myview.TextBody ="SELECT h.SalesOrderID, d.OrderQty FROM
Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON
h.SalesOrderID = d.SalesOrderID"
CREATE VIEW [dbo].[PROV] AS
SELECT drname.dr_id, drname.create_dt, dr_fname, dr_iname, dr_lname,
drtitle, drsuffix, gender, birthdate, marital, ethnic, drname.email,
org_name, dr_ofname, dr_oiname, dr_olname, nationalid, drname.medicare,
drname.medicaid,
CASE
WHEN EXISTS(SELECT 1 FROM stfstatu act WHERE act.dr_id =
drname.dr_id AND fac_cd NOT IN('SMC','WAR','CCS') AND act.active123 IN
('1','3','N','G','6','S','U','CA','TPRO')) THEN 'Y'
ELSE 'N'
END as Active_Status,
a.sch_type as Addr_Type_sch_type, a.addr, a.addr2, a.city,
a.state, a.zip, a.phone, a.fax, a2.tax_id,
(select top 1 rtrim(d.dr_lname) from drname d join address aa
on d.dr_id = aa.dr_id join address2 aa2 on aa.link = aa2.l_address where
d.verfac = 1 and aa2.tax_id = a2.tax_id and drname.verfac = 0) as
Addr_DrPGp,
lan_tab.txt as lan_tab_txt, dr_lan.lan_cd as dr_lan_cd, CASE
WHEN dr_spec.specorder = 1 THEN dr_spec.specialty ELSE '' END as dr_spec,
CASE WHEN dr_spec.PrimSpec = 1 THEN 'P' ELSE '' END as PrimSpec, school.cd
as school_cd, school.txt as school_txt, educate.fdate as educate_fdate,
educate.sch_type, educ_arr.txt as school_type_txt, educate.degree,
educ_tab.txt
as degree_txt, educate.tdate as educate_tdate, CASE WHEN dr_spec.specorder =
1
THEN spec_tab.txt ELSE '' END as spec_Tab_txt,
CASE WHEN stfstatu.pcp_spec = 'B' then 'Yes' WHEN
stfstatu.pcp_spec = 'P' then 'Yes' ELSE 'No' END as PCP,
case when stfstatu.pcp_spec = 'B' then 'PCP and Specialist'
else case when stfstatu.pcp_spec = 'P' then 'PCP'
else case when stfstatu.pcp_spec = 'S' then
'Specialist'
else ''
END
END
END as PCPSpec, taxonomy.cd as tax_cd
FROM drname
JOIN stfstatu on drname.dr_id = stfstatu.dr_id
LEFT JOIN address1 a on drname.dr_id = a.dr_id AND a.sch_type = 'G' AND
a.link = (SELECT TOP 1 link FROM address1 WHERE sch_type = 'G' AND
address1.dr_id = drname.dr_id ORDER BY LINK DESC)
LEFT JOIN address2 a2 on a2.l_address = a.link
LEFT JOIN dr_lan on drname.dr_id = dr_lan.dr_id
LEFT JOIN lan_tab on lan_tab.cd = dr_lan.lan_cd
LEFT JOIN dr_spec on drname.dr_id = dr_spec.dr_id
LEFT JOIN spec_tab on dr_spec.specialty = spec_tab.cd
LEFT JOIN educate on educate.dr_id = drname.dr_id
LEFT JOIN school on educate.cd = school.cd
LEFT JOIN educ_arr on educ_arr.cd = educate.sch_type
LEFT JOIN facility on facility.fac_cd = educate.fac_cd
LEFT JOIN educ_tab on educate.degree = educ_tab.cd
LEFT JOIN taxonomy on taxonomy.dr_id = drname.dr_id
--Where LTRIM(RTRIM(dr_spec.Fac_Cd)) = ''
did you try using the here string (https://www.safaribooksonline.com/library/view/windows-powershell-cookbook/9780596528492/ch05s03.html]) for TextBody?
# Set the TextHeader and TextBody property to define the view.
$myview.TextHeader = "CREATE VIEW [Sales].[Test_View] AS"
$myview.TextBody = #"
SELECT h.SalesOrderID, d.OrderQty FROM
Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON
h.SalesOrderID = d.SalesOrderID
CREATE VIEW [dbo].[PROV] AS
SELECT drname.dr_id, drname.create_dt, dr_fname, dr_iname, dr_lname,
drtitle, drsuffix, gender, birthdate, marital, ethnic, drname.email,
org_name, dr_ofname, dr_oiname, dr_olname, nationalid, drname.medicare,
drname.medicaid,
CASE
WHEN EXISTS(SELECT 1 FROM stfstatu act WHERE act.dr_id =
drname.dr_id AND fac_cd NOT IN('SMC','WAR','CCS') AND act.active123 IN
('1','3','N','G','6','S','U','CA','TPRO')) THEN 'Y'
ELSE 'N'
END as Active_Status,
a.sch_type as Addr_Type_sch_type, a.addr, a.addr2, a.city,
a.state, a.zip, a.phone, a.fax, a2.tax_id,
(select top 1 rtrim(d.dr_lname) from drname d join address aa
on d.dr_id = aa.dr_id join address2 aa2 on aa.link = aa2.l_address where
d.verfac = 1 and aa2.tax_id = a2.tax_id and drname.verfac = 0) as
Addr_DrPGp,
lan_tab.txt as lan_tab_txt, dr_lan.lan_cd as dr_lan_cd, CASE
WHEN dr_spec.specorder = 1 THEN dr_spec.specialty ELSE '' END as dr_spec,
CASE WHEN dr_spec.PrimSpec = 1 THEN 'P' ELSE '' END as PrimSpec, school.cd
as school_cd, school.txt as school_txt, educate.fdate as educate_fdate,
educate.sch_type, educ_arr.txt as school_type_txt, educate.degree,
educ_tab.txt
as degree_txt, educate.tdate as educate_tdate, CASE WHEN dr_spec.specorder =
1
THEN spec_tab.txt ELSE '' END as spec_Tab_txt,
CASE WHEN stfstatu.pcp_spec = 'B' then 'Yes' WHEN
stfstatu.pcp_spec = 'P' then 'Yes' ELSE 'No' END as PCP,
case when stfstatu.pcp_spec = 'B' then 'PCP and Specialist'
else case when stfstatu.pcp_spec = 'P' then 'PCP'
else case when stfstatu.pcp_spec = 'S' then
'Specialist'
else ''
END
END
END as PCPSpec, taxonomy.cd as tax_cd
FROM drname
JOIN stfstatu on drname.dr_id = stfstatu.dr_id
LEFT JOIN address1 a on drname.dr_id = a.dr_id AND a.sch_type = 'G' AND
a.link = (SELECT TOP 1 link FROM address1 WHERE sch_type = 'G' AND
address1.dr_id = drname.dr_id ORDER BY LINK DESC)
LEFT JOIN address2 a2 on a2.l_address = a.link
LEFT JOIN dr_lan on drname.dr_id = dr_lan.dr_id
LEFT JOIN lan_tab on lan_tab.cd = dr_lan.lan_cd
LEFT JOIN dr_spec on drname.dr_id = dr_spec.dr_id
LEFT JOIN spec_tab on dr_spec.specialty = spec_tab.cd
LEFT JOIN educate on educate.dr_id = drname.dr_id
LEFT JOIN school on educate.cd = school.cd
LEFT JOIN educ_arr on educ_arr.cd = educate.sch_type
LEFT JOIN facility on facility.fac_cd = educate.fac_cd
LEFT JOIN educ_tab on educate.degree = educ_tab.cd
LEFT JOIN taxonomy on taxonomy.dr_id = drname.dr_id
--Where LTRIM(RTRIM(dr_spec.Fac_Cd)) = ''
"#

PostgreSQL 9.3: REPLACE string

I have a string to replace with the expected form.
Input: I have the following string.
'A,B,C,D,E,F,G,H,I,J,K,L'
And I want to replace the above string into the following format:
'x.A = z.A ,
x.B = z.B ,
x.C = z.C ,
x.D = z.D ,
x.E = z.E ,
x.F = z.F ,
.........
.........
x.L = z.L'
My try:
SELECT 'x.'||REPLACE('A,B,C,D,E,F,G,H,I,J,K,L',',',' = z.')
SELECT 'x.' || col || '=z.' || col
FROM (
SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) col
) t
You can use string_agg and FORMAT:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , ',')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t
) AS sub;
You can use as delimeter E',\r\n' to get carriage return:
SELECT string_agg(FORMAT('x.%s = z.%s', t,t) , E',\r\n')
FROM (SELECT unnest(regexp_split_to_array('A,B,C,D,E,F,G,H,I,J,K,L', ',')) AS t)
AS sub
Output:
x.A = z.A,
x.B = z.B,
x.C = z.C,
x.D = z.D,
x.E = z.E,
x.F = z.F,
x.G = z.G,
x.H = z.H,
x.I = z.I,
x.J = z.J,
x.K = z.K,
x.L = z.L

Is it possible to have "not in/exists" in one table then in another table?

I'm now maintaining a big app somebody else wrote mining some data from some big government legacy systems. Basically I need a single query result to populate a gridview that takes each part number from a Tech Order and counts matching part numbers in the Fedlog table. If none found then look in the "commercial" table. The existing query currently only looks in the Fedlog table and reads as follows:
select p.*,
(select case when count(*) > 0 then 'Y' else 'N' end as SL
from tbl_fedlog where [Part Number] = p.[Part Number]) as SL
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9' order by p.Figure, p.[Index], p.Indenture
When 'N' I've got to look in the commerical table. Could I have some suggestion on the best way to go about this?
What should the result look like for the 'N' scenario - just another 'Y'/'N' answer? If so, you should be able to simply replace the 'N' expression with another scalar query against the "commercial" table.
Here is a UNION ALL between a Fedlog query and a commercial query, that checks each for existence:
SELECT p.*
, SL = 'Y'
, part_count = (SELECT COUNT(*) FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9'
AND EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
UNION ALL
SELECT p.*
, SL = 'Y'
, part_count = (SELECT COUNT(*) FROM tbl_commercial WHERE [Part Number] = p.[Part Number])
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9'
AND EXISTS(SELECT 1 FROM tbl_commercial WHERE [Part Number] = p.[Part Number])
AND NOT EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
I would need more info to address the 'N' scenario mentioned in other answer though.
If the logic is to display 'Y' when the part exists in either the Fedlog or the Commercial table and 'N' otherwise, then you could try grouping & aggregating those tables separately and (outer-)joining the aggregated result sets to tbl_pcms, like this:
SELECT
p.*,
CASE WHEN COALESCE(f.PartCount, c.PartCount) IS NULL THEN 'N' ELSE 'Y' END AS SL
FROM tbl_pcms p
LEFT JOIN (
SELECT
[Part Number],
COUNT(*) AS PartCount
FROM tbl_fedlog
GROUP BY [Part Number]
) f ON p.[Part Number] = f.[Part Number]
LEFT JOIN (
SELECT
[Part Number],
COUNT(*) AS PartCount
FROM tbl_commercial
GROUP BY [Part Number]
) c ON p.[Part Number] = c.[Part Number]
WHERE p.[Tech Order] = '0B-E0C-9'
ORDER BY
p.Figure,
p.[Index],
p.Indenture

VERY WEIRD T-SQL issue - query works but not if I encapsulate it as a sub-query to just select * from ()

I have the following code which works FANTASTIC. Except - It is a sub-query to another (final) outer query and when I attempt to encapsulate this as a sub-query it refuses to run. To make it simple, I just did a "SELECT * FROM ( MY QUERY HERE)" and that even fails to run. I can only figure I am putting the right ")" in the wrong spot, but I just don't know....
Anyway - this is the query that runs fine till it is a simple sub-query:
SELECT FK_Campaign, FK_Geography, FK_InvoiceDate, FK_SalesType, FK_CustGroup, FK_Customer_Detail, FK_Parent_Detail, FK_Department, FK_Item_Detail,
FK_ItemClass_Detail, FK_ItemGroup_Detail, FK_SalesRep, FK_SalesOrigin, FK_QualityCode, FK_QualityDetailCode, FK_ResponsibilityCode,
FK_NewItemFlag, FK_TransDate, FK_CreatedDate, FK_VMReceivedDate, FK_ReturnAction, FK_StatusCode, ABC.InvoiceId, SalesID, VMRaNumber,
RetDays, ReturnQty, LineAmountmst, Qty, ReturnDays, ReturnLineAmount, ListPrice, ABC.InventTransId, ABC.ItemId,
ZZZ.FK_InventSerialProdDate AS FK_InventSerialProdDate
FROM
(SELECT
ISNULL((SELECT campaignkey --PK_Campaign
FROM VMDWAnalytical.DBO.DIM_Campaign
WHERE CampaignID = ST.smmCampaignID), -99) FK_Campaign,
ISNULL((SELECT PK_Geography
FROM VMDWAnalytical.DBO.DIM_Geography G
WHERE G.Country = ISNULL(CIJ.DLVCountryRegionID, 'zUnknown')
AND G.State = ISNULL(CIJ.DLVState, 'zUnknown')
AND G.Zip = ISNULL(CIJ.DLVZipCode, 'zUnknown')), -99) FK_Geography,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = CIJ.InvoiceDate), 1) FK_InvoiceDate,
ISNULL((SELECT PK_SalesType
FROM VMDWAnalytical.DBO.DIM_SalesType
WHERE SalesType = SL.SalesType), -99) FK_SalesType,
ISNULL((SELECT PK_CustGroup
FROM VMDWAnalytical.DBO.DIM_CustGroup
WHERE CustGroup = CT.CustGroup), -99) FK_CustGroup,
ISNULL((SELECT PK_Customer_Detail
FROM VMDWAnalytical.DBO.DIM_Customer_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Customer_Detail,
ISNULL((SELECT PK_Parent_Detail
FROM VMDWAnalytical.DBO.DIM_Parent_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Parent_Detail,
ISNULL((SELECT PK_Department
FROM VMDWAnalytical.DBO.DIM_Department D
WHERE D.NUM = CIT.Dimension), -99) FK_Department,
ISNULL((SELECT PK_Item_Detail
FROM VMDWAnalytical.dbo.DIM_Item_Detail
WHERE Item = IT.ItemID
AND (ConfigID = ID.ConfigID
OR ConfigID = 'NONE')), -99) FK_Item_Detail,
ISNULL((SELECT PK_ItemClass_Detail
FROM VMDWAnalytical.dbo.DIM_ItemClass_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemClass_Detail,
ISNULL((SELECT PK_ItemGroup_Detail
FROM VMDWAnalytical.dbo.DIM_ItemGroup_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemGroup_Detail,
ISNULL((SELECT PK_SalesRep
FROM VMDWAnalytical.DBO.DIM_SalesRep
WHERE SalesRep = ST.SalesResponsible), -99) FK_SalesRep,
ISNULL((SELECT PK_SalesOrigin
FROM VMDWAnalytical.DBO.DIM_SalesOrigin
WHERE OriginID = ST.SalesOriginID), -99) FK_SalesOrigin,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityCode
FROM VMDWAnalytical.dbo.DIM_QualityCode
WHERE QualityCode = RR.VMQualityCode), -99)
END FK_QualityCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityDetailCode
FROM VMDWAnalytical.dbo.DIM_QualityDetailCode
WHERE QualityDetailCode = SL.VMQualityDetailCode
AND QualityCode = RR.VMQualityCode), -99)
END FK_QualityDetailCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ResponsibilityCode
FROM VMDWAnalytical.dbo.DIM_ResponsibilityCode
WHERE ResponsibilityCode = RR.VMResponsibilityCode), -99)
END FK_ResponsibilityCode,
CASE
WHEN ST.CREATEDDATE <= DATEADD(YEAR, 2, (SELECT KPISTARTDATE FROM RDS_KPIInventTableRel WHERE ITEMID = IT.ITEMID)) THEN
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'NEW')
ELSE
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'EXISTING')
END FK_NewItemFlag,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.TransDate), 1) FK_TransDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.CreatedDate), 1) FK_CreatedDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.VMReceivedDate), 1) FK_VMReceivedDate,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ReturnAction
FROM VMDWAnalytical.dbo.DIM_ReturnAction
WHERE ReturnActionID = RR.ReturnActionID), -99)
END FK_ReturnAction,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_StatusCode
FROM VMDWAnalytical.dbo.DIM_StatusCode
WHERE StatusCode = RR.VMStatusCode), -99)
END FK_StatusCode,
ISNULL(CIT.InvoiceID, 'zUnknown') InvoiceID,
ISNULL(CIT.InventTransId, 'zUnknown') InventTransId,
ISNULL(CIT.ItemId, 'zUnknown') ItemId,
ISNULL(ST.SalesID, 'zUnknown') SalesID,
ISNULL(RR.VMRaNumber, 'zUnknown') VMRaNumber,
CASE
--A, Take out the Service item, flag with -98
WHEN IT.ITEMGROUPID = 'SERVICE' THEN
-98
--B, There is an original SO and the difference between the dates is non-negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE)
--C, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null and the difference between the dates is non-negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE)
--D, There is an original SO and the difference between the dates is negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--E, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null, and the difference between the dates is negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--F, If the campaign date <> 1/1/1900 and the datediff is positive
WHEN (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID) <> '1/1/1900'
AND DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--G, If the difference between the Return SO and the Return and Repair transdate is positive
WHEN DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE) > 0 THEN
DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE)
--H
ELSE
-97
END RETDAYS,
--RETURNS
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.LINEAMOUNTMST
ELSE
0
END) AS ReturnLineAmount,
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.QTY
ELSE
0
END) AS ReturnQty,
--/RETURNS
(CIT.LINEAMOUNTMST) AS LineAmountMst, --Measure
(CIT.QTY) AS Qty, --Measure
ISNULL(DATEDIFF(DAY, RR.CreatedDate, RR.TransDate), 0) ReturnDays,
ITMS.PRICE AS ListPrice --Measure
FROM RDS_CUSTINVOICETRANS CIT
LEFT JOIN RDS_CUSTINVOICEJOUR CIJ
ON CIT.INVOICEID = CIJ.INVOICEID
JOIN RDS_CUSTTABLE CT
ON CIJ.ORDERACCOUNT = CT.ACCOUNTNUM
LEFT JOIN RDS_ADDRESSCOUNTRYREGION ACR
ON CIJ.DLVCOUNTRYREGIONID = ACR.COUNTRYREGIONID
LEFT JOIN RDS_SALESTABLE ST
ON CIJ.SALESID = ST.SALESID
LEFT JOIN RDS_SALESLINE SL
ON CIT.INVENTTRANSID = SL.INVENTTRANSID
LEFT JOIN RDS_INVENTTABLE IT
ON CIT.ITEMID = IT.ITEMID
LEFT JOIN RDS_INVENTTABLEMODULE ITMS
ON IT.ITEMID = ITMS.ITEMID
AND ITMS.MODULETYPE = 2
LEFT JOIN RDS_VMRETURNANDREPAIRTABLE RR
ON SL.SALESID = RR.SALESID
AND SL.VMRANUMBER = RR.VMRANUMBER
LEFT JOIN RDS_INVENTDIM ID
ON SL.INVENTDIMID = ID.INVENTDIMID
) ABC
--WHERE SL.SALESTYPE = 4 --and (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NULL
LEFT JOIN
(SELECT CIT.InventTransId AS InventTransId, CIT.ItemId AS ItemId, CIT.InvoiceId AS InvoiceId,
ISNULL((SELECT T.TIMEKEY
FROM VMDWANAlytical.DBO.DIM_Time T
WHERE T.FullDate = MAX(SR.ProdDate)),1) AS FK_InventSerialProdDate
FROM RDS_CustInvoiceTrans CIT
LEFT JOIN RDS_InventTrans IVT
ON CIT.InventTransId = IVT.InventTransId AND
CIT.InvoiceId = IVT.InvoiceId AND
CIT.ItemId = IVT.ItemId
LEFT JOIN RDS_INVENTDIM ID
ON IVT.InventDimId = ID.InventDimId
LEFT JOIN RDS_InventSerial SR
ON ID.InventSerialId = SR.InventSerialId AND
IVT.ItemId = SR.ItemId
GROUP BY CIT.InventTransId, CIT.ItemId, CIT.InvoiceId) ZZZ
ON ABC.InventTransId = ZZZ.InventTransId AND
ABC.ItemId = ZZZ.ItemId AND
ABC.InvoiceId = ZZZ.InvoiceId
I think you need to add an alias to the subquery so you'd have
SELECT * FROM ( MY QUERY HERE) as MyQuery