user variables in a calculation - mysqli

I am producing a league table for speedway teams, I have got a query to calculate the required data based on teams results. The part I am struggling with is the points difference (difference between points scored and scored against.
SELECT tbl_clubs.club, tbl_clubs.club_id,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore is not null ,1,0)) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.homescore is not null,1,0 )) as `M`,
SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore > tbl_fixtures.awayscore, 1, 0 ) ) AS `W`,
SUM( IF( tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) AS `HD`,
SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore < tbl_fixtures.awayscore, 1, 0 ) ) AS `HL`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore >=7,1,0)) AS `4W`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore <=6,1,0)) AS `3W`,
SUM( IF( tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) AS `AD`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore <=6,1,0)) AS `1L`,
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore >=7,1,0)) AS `L`,
#FOR:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.homescore,0)) as `F`,
#Against:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.homescore,0)) as `A`,
SUM(#For - #Against) as `PtsDiff`,
SUM( if( tbl_clubs.club_id = tbl_fixtures.home
AND tbl_fixtures.homescore > tbl_fixtures.awayscore, 3, 0 ) ) +
SUM( IF( tbl_clubs.club_id = tbl_fixtures.home AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 1, 0 ) ) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore >=7,4,0)) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore > tbl_fixtures.homescore
AND tbl_fixtures.awayscore - tbl_fixtures.homescore <=6,3,0)) +
SUM( IF( tbl_clubs.club_id = tbl_fixtures.away AND tbl_fixtures.awayscore = tbl_fixtures.homescore, 2, 0 ) ) +
SUM(if(tbl_clubs.club_id = tbl_fixtures.away
AND tbl_fixtures.awayscore < tbl_fixtures.homescore
AND tbl_fixtures.homescore - tbl_fixtures.awayscore <=6,1,0)) as `Pts`
FROM tbl_clubs
INNER JOIN tbl_fixtures ON tbl_clubs.club_id = tbl_fixtures.home
OR tbl_clubs.club_id = tbl_fixtures.away
where tbl_clubs.league_id = 3
GROUP BY tbl_clubs.club_id
order by Pts desc, PtsDiff desc, club asc
All of the query is working except for
#FOR:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.homescore,0)) as `F`,
#Against:=SUM(IF(tbl_clubs.club_id = tbl_fixtures.home,tbl_fixtures.awayscore,0)) +
SUM(IF(tbl_clubs.club_id = tbl_fixtures.away,tbl_fixtures.homescore,0)) as `A`,
SUM(#For - #Against) as `PtsDiff`,
I am getting NULL as a result for this, I am guessing its something simple, any help would be great

Firstly, you'll want to ensure that null values always default to 0 and not null. This is something that could happen within your script, so you should ensure that 0 is the only viable default. This should occur before this query gets executed though ideally. It doesn't appear that this is the case based on your script, so you may want to ensure you have designed your database to cater for that.
Secondly, variable assignment inside queries is not quite as straight-forward as you'd like it to be unfortunately. You may be better using a sub-query for your initialisations:
#FOR:=(select IFNULL(SUM(tbl_fixtures.awayscore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.away) +
(select IFNULL(SUM(tbl_fixtures.homescore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.home)
as `F`,
#Against:=(select IFNULL(SUM(tbl_fixtures.awayscore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.home) +
(select IFNULL(SUM(tbl_fixtures.homescore),0) from tbl_fixtures where tbl_clubs.club_id = tbl_fixtures.away)
as `A`,
SUM(#FOR - #Against) as `PtsDiff`,
Not very elegant, but this should work. Notice the use of IFNULL to ensure that null is converted to 0.

Related

How to convert case else to when otherwise in spark dataframes

I would like to rewrite teradata code to spark dataframes using scala, facing an error " when() cannot be applied once otherwise() is applied ", Help is appreciated.
Teradata
CASE WHEN
CASE WHEN ID <> cid OR Group <> sg OR ead IS NULL THEN 1
ELSE
CASE WHEN HFlag <> hg AND ad + TBreak < ActivityDate THEN 1
ELSE
CASE WHEN HFlag = hg AND HFlag = 1 THEN
CASE WHEN ead + 1 < ActivityDate THEN
CASE WHEN ead + TBreak < ActivityDate THEN 1
ELSE 0 END
ELSE 0 END
WHEN HFlag = hg AND HFlag = 0 THEN
CASE WHEN ead + TBreak < ActivityDate THEN 1
ELSE 0 END
ELSE 0 END
END
END = 1 THEN Row_Number() Over(ORDER BY ID, Group, ActivityDate, HFlag)
ELSE 0 END AS arctic
I tried in the below way.
val windowRank = Window.orderBy('ID, 'Group, 'ActivityDate, 'HFlag)
df.withColumn("arctic",
when(when(col("ID") =!= col("cid") || col("Group") =!= col("sg") || col("ad").isNull, 1)
.when(col("HFlag") =!= col("hg") && (col("ad") + col("TBreak")) < col("ActivityDate"), 1)
.when(col("HFlag") === col("hg") && col("HFlag") === 1,
when((col("ad") + 1) < col("ActivityDate"),
when((col("ad") + col("TBreak")) < col("ActivityDate"), 1)
.otherwise(0))
.otherwise(0)
.when(col("HFlag") === col("hg") && col("HFlag") === 0, when((col("ad") + col("TBreak")) < col("ActivityDate"), 1))
.otherwise(0))
.otherwise(0) === 1, row_number() over windowRank)
.otherwise(0))
You have missed a closing bracket
val windowRank = Window.orderBy('ID, 'Group, 'ActivityDate, 'HFlag)
df.withColumn("arctic",
when(when(col("ID") =!= col("cid") || col("Group") =!= col("sg") || col("ad").isNull, 1)
.when(col("HFlag") =!= col("hg") && (col("ad") + col("TBreak")) < col("ActivityDate"), 1)
.when(col("HFlag") === col("hg") && col("HFlag") === 1,
when((col("ad") + 1) < col("ActivityDate"),
when((col("ad") + col("TBreak")) < col("ActivityDate"), 1)
.otherwise(0))
.otherwise(0)) // <-- missing close bracket
.when(col("HFlag") === col("hg") && col("HFlag") === 0, when((col("ad") + col("TBreak")) < col("ActivityDate"), 1))
.otherwise(0))
.otherwise(0) === 1, row_number() over windowRank)
.otherwise(0))

Convert an iteration to recursion

I have an iteration logic that returns a query like this :
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val reprocessDate ="2018-10-24"
for( i <- 0 to level){
var currLevelSubQuery=""
if (i==0 ){
currLevelSubQuery= baseQuery + s"$i and agg_value >= '${reprocessDate}'"
}
else{
currLevelSubQuery= baseQuery + s"$i and parent_agg_id in ( $prevLevelSubQuery )"
}
prevLevelSubQuery= currLevelSubQuery
finalQuery = finalQuery + currLevelSubQuery + (if (i<level) " union " else "")
}
It returns a query of this nature for level = 2.
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >= '2018-10-24'
UNION
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 1
AND parent_agg_id IN (SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >= '2018-10-24')
UNION
SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 2
AND parent_agg_id IN (SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 1
AND parent_agg_id IN
(SELECT agg_id
FROM quality.quality_aggregator
WHERE job_id = 123
AND level = 0
AND agg_value >=
'2018-10-24'))
I am trying to convert it into a recursive logic like this
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val finalQuery = getAggIdSQLGenerator(2,"2018-10-24")
def getAggIdSQLGenerator(level : Int, reprocessDate:String):String={
if (level == 0)
( baseQuery + s"$level and agg_value >= '${reprocessDate}'")
else
{
val subQuery=getAggIdSQLGenerator(level-1 ,reprocessDate)
baseQuery + s"$level and parent_agg_id in (" +subQuery +") union "+ subQuery
}
}
But this is not yielding correct results. What am I missing?
This isn't recursive but I think it's a smaller, cleaner, implementation of what you're after.
val baseQuery = ".... level="
val levelRE = "level=(\\d+)".r.unanchored
val reprocessDate ="2018-10-24"
val av = s" and agg_value >= '${reprocessDate}'"
val pai = " and parent_agg_id in "
val itrs = 3
val query = List.iterate(s"${baseQuery}0$av", itrs) { prevStr =>
val level = prevStr match {
case levelRE(n) => n.toInt + 1
case _ => 0
}
s"$baseQuery$level$pai($prevStr)"
}.mkString(" union ")
The issue is you have added union on every query and you have concatenated subquery 2 times.
This gives your expected output.
val baseQuery = s"select agg_id from quality.QUALITY_AGGREGATOR where job_id = 123 and level ="
val finalQuery = getAggIdSQLGenerator(2, "2018-10-24")
def getAggIdSQLGenerator(level: Int, reprocessDate: String): String = {
if (level == 0) {
baseQuery + s" $level and agg_value >= '${reprocessDate}'"
} else {
val subQuery = getAggIdSQLGenerator(level - 1, reprocessDate)
baseQuery + s" $level and parent_agg_id in (" + subQuery + ")"
}
}
println("UNION " + finalQuery)

Combining Two Queries and Calculating Result

I am attempting to calculate the difference between query 1:
select case
when cnt >= 1 AND cnt <= 2000 then cnt * 6
when cnt >= 2001 AND cnt <= 4000 then ((cnt - 2000) * 5) + 12000
when cnt >= 4001 AND cnt <= 6000 then ((cnt - 4000) * 4) + 22000
when cnt >= 6001 AND cnt <= 8000 then ((cnt - 6000) * 3) + 30000
when cnt >= 8001 then ((cnt - 8000) * 2) + 36000
else 1
end "Customer Investment"
from (
select COUNT(*) as cnt
from "mv_fundraiser_report"
where thank_you_delivered = true
[[AND {{NonProfit}}]]
[[AND {{StartDate}}]]
) t
And Query 2:
SELECT ((cast(A.TNUM as float)/cast(A.TDENOM as float))-(cast(A.FNUM as float)/cast(A.FDENOM as float)))*cast(A.TDENOM as float) AS "Heck"
FROM (SELECT
(SELECT SUM("public"."mv_fundraiser_report"."total_raised")
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = FALSE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS FNUM,
(SELECT count(*) AS "count"
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = FALSE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS FDENOM,
(SELECT SUM("public"."mv_fundraiser_report"."total_raised")
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = TRUE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS TNUM,
(SELECT count(*) AS "count"
FROM "public"."mv_fundraiser_report"
WHERE ("public"."mv_fundraiser_report"."opt-in" = TRUE
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 704943916598630
AND NOT "public"."mv_fundraiser_report"."campaign_id" = 193572775319413
AND NOT(first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])) AS TDENOM) A
Both of the queries work by themselves and return a single number, but I am struggling heavily with the syntax. I'm totally unsure of how I can make use of (window?) functions in order to achieve my end result. Any help is appreciated, thanks!
You can place each query into common table expressions, then subtract one from the other.
For example (reworked query 2 for simplification):
WITH one AS (
SELECT
CASE
WHEN cnt >= 1 AND cnt <= 2000 THEN cnt * 6
WHEN cnt >= 2001 AND cnt <= 4000 THEN ((cnt - 2000) * 5) + 12000
WHEN cnt >= 4001 AND cnt <= 6000 THEN ((cnt - 4000) * 4) + 22000
WHEN cnt >= 6001 AND cnt <= 8000 THEN ((cnt - 6000) * 3) + 30000
WHEN cnt >= 8001 THEN ((cnt - 8000) * 2) + 36000
ELSE 1
END "Customer Investment"
FROM (
SELECT COUNT(*) as cnt
FROM "mv_fundraiser_report"
WHERE thank_you_delivered = true
[[AND {{NonProfit}}]]
[[AND {{StartDate}}]]
) t
),
two AS (
SELECT (
(
SUM(public.mv_fundraiser_report.total_raised)
FILTER (WHERE public.mv_fundraiser_report.opt-in = FALSE)
)::float AS FNUM /
(
count(*)
FILTER (WHERE public.mv_fundraiser_report.opt-in = FALSE)
)::float AS FDENOM
) -
(
(
SUM(public.mv_fundraiser_report.total_raised)
FILTER (WHERE public.mv_fundraiser_report.opt-in = TRUE)
)::float AS TNUM /
(
count(*)
FILTER (WHERE public.mv_fundraiser_report.opt-in = TRUE)
)::float AS TDENOM
) AS "Heck"
FROM public.mv_fundraiser_report
WHERE NOT public.mv_fundraiser_report.campaign_id = 704943916598630
AND NOT public.mv_fundraiser_report.campaign_id = 193572775319413
AND NOT (first_name IS NULL
AND total_raised > 1000
AND fundraiser_type = 'Generic Fundraiser')
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]])
)
SELECT one."Customer Investment" - two."Heck" AS difference
FROM one, two;
I don't have your data or schema to test this against, so this untested.

SQR CASE STATEMENT GIVING ERROR WHEN LOCAL VARIABLE IS USED

I need to use a date variable in a case statement for the select section of a sql statement in sqr and keep getting an error. It works fine when i use the getdate() function to compare but doesn't work with my variable. help please. code is included.
BEGIN-SELECT
DBO.GET_XLAT_DESC(A.TPD_PARISH,'TPD_PARISH') "DESCR" &LABEL_DESCR (+2,4)
COUNT(1) "CNT" &ENT_CNT (,23) ! total entities matching base criteria
COUNT(CASE WHEN B.ATTACH_TYPE_CD = 'PHC' AND B.EXPIRATION_DATE >= getdate()
THEN 1 END) "HEALTH_PST" &H_PAST (,34)
COUNT(CASE WHEN B.ATTACH_TYPE_CD = 'PHC' AND B.EXPIRATION_DATE >= $curr_dte
THEN 1 END) "HEALTH_CUR" &H_CURR (,44)
COUNT(CASE WHEN B.ATTACH_TYPE_CD = 'PHC' AND B.EXPIRATION_DATE >=
DATEADD($START_DATE,'MONTH',-1) THEN 1 END) "HEALTH_FTR" &H_FUTR
let #region_total = #region_total + #ent_total
PRINT #ent_total (, 235) EDIT 999,999 BOLD
FROM PS_TPD_ENTITY A LEFT JOIN PS_TPD_ENT_ATTACH B ON A.TPD_ENTITY =
B.TPD_ENTITY
WHERE $TPD_REPORT_TYPE = 'P'
AND (RTRIM(LTRIM(UPPER(A.TPD_ENT_STATUS))) = $TPD_ENT_STATUS OR
$TPD_ENT_STATUS ='')
AND (RTRIM(LTRIM(UPPER(A.TPD_ENTITY_TYPE))) = $TPD_ENTITY_TYPE OR
$TPD_ENTITY_TYPE ='')
AND (RTRIM(LTRIM(UPPER(A.REGION))) = $REGION OR $REGION ='')
AND (RTRIM(LTRIM(UPPER(A.TPD_PARISH))) = $TPD_PARISH OR $TPD_PARISH ='')
GROUP BY A.TPD_PARISH
order BY DESCR
Thank you Cardmagik. This worked for me. The code that worked is below. I substituted the entire select column section one by one.
let $curr_dte = edit($START_DATE,'yyyymmdd')
let #ent_cnt = 0
let $h_past =
'COUNT(CASE WHEN B.ATTACH_TYPE_CD = ''PHC'' AND'
let $h_past = $h_past || ' B.EXPIRATION_DATE >= DATEADD(MONTH,-1,'''||
$CURR_DTE
let $h_past = $h_past || ''') THEN 1 END)'
let $h_curr = 'COUNT(CASE WHEN B.ATTACH_TYPE_CD = ''PHC'' AND' let $h_curr =
$h_curr || ' B.EXPIRATION_DATE >= '''|| $CURR_DTE
let $h_curr = $h_curr ||
''' THEN 1 END)'
let $get_parish_count = 'DBO.GET_ENTITY_COUNT(''P'','''||$TPD_ENT_STATUS
let $get_parish_count = $get_parish_count || ''' , '''||$TPD_ENTITY_TYPE
let $get_parish_count = $get_parish_count || ''' , A.TPD_PARISH, NULL)'
begin-procedure parish_rpt
BEGIN-SELECT
DBO.GET_XLAT_DESC(A.TPD_PARISH,'TPD_PARISH') "DESCR" &LABEL_DESCR (+2,4)
A.TPD_PARISH &location_code
[$get_parish_count] &ENT_CNT=NUMBER (,24)
[$h_past] &H_PAST=NUMBER (,34)
[$h_curr] &H_CURR=NUMBER (,44)
FROM PS_TPD_ENTITY A LEFT JOIN PS_TPD_ENT_ATTACH B ON A.TPD_ENTITY =
B.TPD_ENTITY
WHERE $TPD_REPORT_TYPE = 'C'
AND (RTRIM(LTRIM(UPPER(A.TPD_ENT_STATUS))) = $TPD_ENT_STATUS OR
$TPD_ENT_STATUS ='')
AND (RTRIM(LTRIM(UPPER(A.TPD_ENTITY_TYPE))) = $TPD_ENTITY_TYPE OR
$TPD_ENTITY_TYPE ='')
AND (RTRIM(LTRIM(UPPER(A.REGION))) = $REGION OR $REGION ='')
AND (RTRIM(LTRIM(UPPER(A.TPD_PARISH))) = $TPD_PARISH OR $TPD_PARISH ='')
GROUP BY A.TPD_PARISH
ORDER BY DESCR
END-SELECT
end-procedure

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