joining two tables using CTE - tsql

I have two queries return following output: T1 and T2
Now I would like to join both tables on the T1.CMonth and T2.DueMonth fields.
The Final output should be as shown in the png.
The query for T1:
SELECT WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) AS CMonth,
COUNT(CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)) AS Total_Complete
FROM WorkManagementAsset INNER JOIN
WorkOrder ON WorkManagementAsset.Oid = WorkOrder.Asset INNER JOIN
WorkItem ON WorkOrder.Oid = WorkItem.WorkOrder INNER JOIN
InspectionDefectItem ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid = InspectionDefectItem.WorkItem
WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
GROUP BY WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)
HAVING (WorkManagementAsset.AssetCategory = N'sealedroads') AND (NOT (CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4),
WorkItem.CompleteDate, 120) IS NULL))
The Query for T2:
SELECT WorkManagementAsset.AssetCategory, CONVERT(CHAR(4),
WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) AS
DueMonth,
COUNT(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)) AS Total_DUE FROM WorkManagementAsset INNER JOIN
WorkOrder ON WorkManagementAsset.Oid = WorkOrder.Asset INNER JOIN
WorkItem ON WorkOrder.Oid = WorkItem.WorkOrder INNER JOIN
InspectionDefectItem ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid =
InspectionDefectItem.WorkItem WHERE (NOT
(InspectionDefectItem.DefectGroupName LIKE N'Re%')) GROUP BY
WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.DueDate,
100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) HAVING
(WorkManagementAsset.AssetCategory = N'sealedroads') AND
(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4),
WorkItem.DueDate, 120) <> '0')
Any help would be highly appreciated.
Thanks
Tables and Output

This
WITH T1 AS
(
SELECT
WorkManagementAsset.AssetCategory,
CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) AS CMonth,
COUNT(CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)) AS Total_Complete
FROM WorkManagementAsset
INNER JOIN WorkOrder
ON WorkManagementAsset.Oid = WorkOrder.Asset
INNER JOIN WorkItem
ON WorkOrder.Oid = WorkItem.WorkOrder
INNER JOIN InspectionDefectItem
ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid = InspectionDefectItem.WorkItem
WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
GROUP BY
WorkManagementAsset.AssetCategory,
CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)
HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
AND (NOT (CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) IS NULL))
),
T2 AS
(
SELECT
WorkManagementAsset.AssetCategory,
CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) AS DueMonth,
COUNT(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)) AS Total_DUE
FROM WorkManagementAsset
INNER JOIN WorkOrder
ON WorkManagementAsset.Oid = WorkOrder.Asset
INNER JOIN WorkItem
ON WorkOrder.Oid = WorkItem.WorkOrder
INNER JOIN InspectionDefectItem
ON WorkItem.DefectItem = InspectionDefectItem.Oid
AND WorkItem.Oid = InspectionDefectItem.WorkItem
WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
GROUP BY WorkManagementAsset.AssetCategory,
CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)
HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
AND (CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) <> '0')
)
SELECT *
FROM T1
INNER JOIN T2 ON T1.CMonth = T2.DueMonth;
Note that this is a horrifically inefficient query for numerous reasons.

Related

How to factor this postgis query with subquery?

I have a query to found POIs around trace :
SELECT
ptb.* AS pois
FROM traces tr, pois pta, pois ptb
WHERE tr.id = #{trace.id}
AND pta.id = #{poi.id}
AND ST_DWithin(
ST_LineSubstring(
tr.path,
ST_LineLocatePoint(tr.path, pta.lonlat::geometry) + (#{dist} * 1000) / ST_Length(tr.path, false),
ST_LineLocatePoint(tr.path, pta.lonlat::geometry) + (#{end_point} * 1000) / ST_Length(tr.path, false)
)::geography,
ptb.lonlat::geography,
4000)
How can I use subquery for :
ST_LineLocatePoint(tr.path, pta.lonlat::geometry)
ST_Length(tr.path, false)
EDIT :
WITH RECURSIVE locate_point_a AS (
select ST_LineLocatePoint(tr.path, pta.lonlat::geometry) AS locate_point_a
FROM traces tr, pois pta
WHERE tr.id = 2
AND pta.id = 2
)
SELECT
ptb.* AS pois
FROM traces tr, pois pta, pois ptb, locate_point_a
WHERE tr.id = 2
AND pta.id = 2
AND ST_DWithin(
ST_LineSubstring(
tr.path,
locate_point_a + (25 * 1000) / ST_Length(tr.path, false),
locate_point_a + (250 * 1000) / ST_Length(tr.path, false)
)::geography,
ptb.lonlat::geography,
4000)
SQL
This should do the same (but I do not understand the logic, TBH):
SELECT
ptb.* -- AS pois
FROM pois ptb
WHERE EXISTS (
SELECT *
FROM traces tr
JOIN pois pta ON ST_DWithin(
ST_LineSubstring( tr.path
, ST_LineLocatePoint(tr.path, pta.lonlat::geometry) + (#{dist} * 1000) / ST_Length(tr.path, false)
, ST_LineLocatePoint(tr.path, pta.lonlat::geometry) + (#{end_point} * 1000) / ST_Length(tr.path, false)
)::geography
, ptb.lonlat::geography
, 4000
)
WHERE tr.id = #{trace.id}
AND pta.id = #{poi.id}
;

PostgreSQL Median without using percentile function

To calculate the median for even number of rows, I know I have to divide the RowNum by 2. I don't understand why I need the "+1" and "+2" inside "WHERE RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)". Can't I just write "WHERE RowNum IN ((RowCnt) / 2, (RowCnt) / 2)" instead?
with t1 as
(select *,
row_number() over(order by hourly_pay) as RowNum,
count(*) over() as RowCnt
from employee_data)
select *
from t1
WHERE RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)
Video of me explaining my confusion: https://streamable.com/mv2vj

Using aggregate functions on alias?

I want to make a query where I am computing the difference between two columns. Something like:
SELECT a,
b,
a - b as "diff"
FROM ...
Now I would like to calculate the stddev of the "diff" column using postgresql built-in stddev aggregate function. How can I achieve this?
Thanks.
EDIT:
The actual query is this:
SELECT tr.date_start,
tr.date_end,
(((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tr.amt_won + tr.cnt_bounty * tourney_summary.amt_bounty) ELSE 0.0 END))) AS "amt_won_curr_conv",
(((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tourney_summary.amt_buyin + tourney_summary.amt_fee + tourney_summary.amt_rebuy * tr.cnt_rebuy + tourney_summary.amt_addon * tr.cnt_addon + tourney_summary.amt_bounty) ELSE 0.0 END))) AS "amt_buyin_ttl_curr_conv",
((((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tr.amt_won + tr.cnt_bounty * tourney_summary.amt_bounty) ELSE 0.0 END))) - (((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tourney_summary.amt_buyin + tourney_summary.amt_fee + tourney_summary.amt_rebuy * tr.cnt_rebuy + tourney_summary.amt_addon * tr.cnt_addon + tourney_summary.amt_bounty) ELSE 0.0 END)))) as net_amt_won,
stddev((((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tr.amt_won + tr.cnt_bounty * tourney_summary.amt_bounty) ELSE 0.0 END))) - (((CASE when(tourney_summary.val_curr_conv != 0) THEN tourney_summary.val_curr_conv * (tourney_summary.amt_buyin + tourney_summary.amt_fee + tourney_summary.amt_rebuy * tr.cnt_rebuy + tourney_summary.amt_addon * tr.cnt_addon + tourney_summary.amt_bounty) ELSE 0.0 END)))) as diff_std_dev
FROM tourney_summary,
tourney_results tr
WHERE
tr.id_player=1
AND tourney_summary.id_tourney = tr.id_tourney
AND ((tourney_summary.id_gametype = 1)
AND (((((((tourney_summary.id_table_type IN
(SELECT lttt.id_table_type
FROM tourney_table_type lttt
WHERE lttt.val_seats = 2))))))
AND (((((tourney_summary.id_table_type IN
(SELECT lttt.id_table_type
FROM tourney_table_type lttt
WHERE position('S' IN lttt.val_speed) > 0))
OR (tourney_summary.id_table_type IN
(SELECT lttt.id_table_type
FROM tourney_table_type lttt
WHERE position('H' IN lttt.val_speed) > 0))))))))
AND ((tourney_summary.date_start >= '2013/08/15 23:00:00')))
GROUP BY tr.date_start,
tr.date_end,
tourney_summary.val_curr_conv,
tr.amt_won,
tr.cnt_bounty,
tourney_summary.amt_bounty,
tourney_summary.amt_buyin,
tourney_summary.amt_fee,
tourney_summary.amt_rebuy,
tr.cnt_rebuy,
tourney_summary.amt_addon,
tr.cnt_addon
ORDER BY tr.date_end DESC;
The "a" and "b" expressions (the ones with CASE) are big. And I don't know how to avoid the copy/paste. In any case using stddev on the a-b expression returns a blank column. What am I doing wrong?
Thanks.
You pretty much answer it yourself. Calculate the standard deviation of the difference:
SELECT a,
b,
a - b as "diff",
stddev(a - b) AS "diff_stddev"
FROM ...
If a - b is a computationally expensive operation or is in fact a much more complex expression in reality, you can wrap it in a subquery:
SELECT a, b, "diff", stddev("diff") AS diff_stddev
FROM (
SELECT a, b, a - b
FROM ...
) x (a, b, "diff")
x is just a throw-away alias for the subquery table.
it's also possible to do this with cte
with cte1 as (
select a, b, a - b as diff
from ...
)
select
a, b, diff, stddev(diff) as diff_stddev
from cte1

Not all items in Order by are in Select

SELECT DISTINCT f.FoodNumber,
f.FoodID,
fn.Name AS FoodName,
d.[Description],
substring(n.Note, CHARINDEX(']', n.Note) + 2,
LEN(n.Note)) AS FoodNote
FROM Food f
JOIN FoodName fn
ON fn.FoodNameID = f.FoodNameID
JOIN FoodPart fp
ON fp.FoodID = p.FoodID
JOIN [Application] a
ON a.ApplicationID = fn.ApplicationID
LEFT JOIN [Description] d
ON d.DescriptionID = ap.DescriptionID
JOIN Note n
ON n.NoteID = a.NoteID
JOIN FoodYear fy
ON fy.FoodYearID = a.FoodYearID
WHERE mmy.FoodlId = 33997332
ORDER BY CASE
WHEN substring(n.Note, 1, 1) = 'A' THEN 1
WHEN substring(n.Note, 1, 1) = 'Y' THEN 2
WHEN substring(n.Note, 1, 1) = 'D ' THEN 3
END,
f.FoodNumber,
f.FoodID,
fn.Name,
d.[description],
substring(n.Note, CHARINDEX(']', n.Note) + 2, LEN(n.Note))
I keep getting an error saying not all the items in the order by are in the select list.
UPDATE
This works but I'm getting dup part numbers listed...I can't add distinct or it will complain that I don't have something in the select list for the order by
select ap.applicationID,
ap.NoteID,
f.FoodNumber,
n.Note as PartNote,
f.FoodID,
q.Quantity,
fn.Name as FoodName,
d.[Description]
from Food f
join FoodName fn on fn.FoodNameID = f.FoodNameID
join FoodPart fp on fp.partID = f.FoodID
join Quantity q on q.QuantityID = ap.QuantityID
join [Application] a on a.ApplicationID = ap.ApplicationID
left join [Description] d on d.DescriptionID = ap.DescriptionID
join Note n on n.NoteID = ap.NoteID
join Note n2 on n2.NoteID = a.NoteID
join FoodYear fy on fy.FoodYearID = a.FoodYearID
join Model mo on mo.ModelID = fy.ModelID
where fy.ModelId = #ModelId
order by
case when substring(f.FoodNumber, 1, 1) = 'T' then 1
when substring(f.FoodNumber, 1, 1) = 'R' then 2
when substring(f.FoodNumber, 1, 1) = 'C' then 3
else
substring(f.FoodNumber, 1, 1)
END,
f.FoodNumber asc,
f.FoodID,
fn.Name ,
d.[description],
substring(n.Note, CHARINDEX(']', n.Note) + 2, LEN(n.Note))
You need to add SUBSTRING(n.Note, 1, 1) to the SELECT list or remove the DISTINCT.
You currently are doing DISTINCT on SUBSTRING(n.Note, CHARINDEX(']', n.Note) + 2, LEN(n.Note)) AS FoodNote but there can be multiple possible SUBSTRING(n.Note, 1, 1) values that all map to the same value for that.
WITH n(Note) AS
(
SELECT '' UNION ALL
SELECT 'A' UNION ALL
SELECT ']'
)
SELECT SUBSTRING(n.Note, CHARINDEX(']', n.Note) + 2,
LEN(n.Note)) AS FoodNote
,SUBSTRING(n.Note, 1, 1) AS SS
FROM n
Returns
FoodNote SS
-------- ----
A
]
You can also use GROUP BY instead of DISTINCT and ORDER BY MIN(SUBSTRING(n.Note, 1, 1)) so the expression becomes unambiguous in that event and is allowed.
i.e. something like
;WITH CTE AS
(
SELECT
f.FoodNumber,
f.FoodID,
fn.Name AS FoodName,
d.[Description],
substring(n.Note, CHARINDEX(']', n.Note) + 2,
LEN(n.Note)) AS FoodNote,
substring(n.Note, 1, 1) AS N1
FROM Food f
JOIN FoodName fn
ON fn.FoodNameID = f.FoodNameID
JOIN FoodPart fp
ON fp.FoodID = p.FoodID
JOIN [Application] a
ON a.ApplicationID = fn.ApplicationID
LEFT JOIN [Description] d
ON d.DescriptionID = ap.DescriptionID
JOIN Note n
ON n.NoteID = a.NoteID
JOIN FoodYear fy
ON fy.FoodYearID = a.FoodYearID
WHERE mmy.FoodlId = 33997332
)
SELECT FoodNumber,
FoodID,
FoodName,
[Description],
FoodNote
FROM CTE
GROUP BY FoodNumber,
FoodID,
FoodName,
[Description],
FoodNote
ORDER BY CASE
WHEN MIN(N1) = 'A' THEN 1
WHEN MIN(N1) = 'Y' THEN 2
WHEN MIN(N1) = 'D ' THEN 3
END,
FoodNumber,
FoodID,
FoodName,
[Description],
FoodNote
perhaps add
case when when substring(n.Note, 1, 1) = 'A' then 1
when substring(n.Note, 1, 1) = 'Y' then 2
when substring(n.Note, 1, 1) = 'D ' then 3
END,
to your select?
Though I dind't think an order by required something to be in the select.
Also: you don't have a else in the case for if note is not A Y or D.

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