SQL Server 2008 r2 CASE Expression not evaluating correctly - sql

I've got the following SQL statement that is not determining when a field has a value of 'Y' when it should. Here is the SQL...
SELECT A.BUSINESS_UNIT
, A.WO_ID
, A.WO_TASK_ID
, A.ENS_TSK_CRT_VAL
, (CASE WHEN A.ENS_TSK_CRT_V01 = 'Y' THEN B.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V01
, (CASE WHEN A.ENS_TSK_CRT_V02 = 'Y' THEN C.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V02
, (CASE WHEN A.ENS_TSK_CRT_V03 = 'Y' THEN D.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V03
, (CASE WHEN A.ENS_TSK_CRT_V04 = 'Y' THEN E.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V04
, (CASE WHEN A.ENS_TSK_CRT_V05 = 'Y' THEN F.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V05
, (CASE WHEN A.ENS_TSK_CRT_V06 = 'Y' THEN G.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V06
, (CASE WHEN A.ENS_TSK_CRT_V07 = 'Y' THEN H.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V07
, (CASE WHEN A.ENS_TSK_CRT_V08 = 'Y' THEN I.DESCR ELSE ' ' END) AS ENS_TSK_CRT_V08
FROM PS_ENS_WM_TSKCR_VW A LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '01' ) B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT
AND B.WO_ID = A.WO_ID
AND B.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '02' ) C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT
AND C.WO_ID = A.WO_ID
AND C.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '03' ) D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT
AND D.WO_ID = A.WO_ID
AND D.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '04' ) E ON E.BUSINESS_UNIT = A.BUSINESS_UNIT
AND E.WO_ID = A.WO_ID
AND E.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '05' ) F ON F.BUSINESS_UNIT = A.BUSINESS_UNIT
AND F.WO_ID = A.WO_ID
AND F.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '06' ) G ON G.BUSINESS_UNIT = A.BUSINESS_UNIT
AND G.WO_ID = A.WO_ID
AND G.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '07' ) H ON H.BUSINESS_UNIT = A.BUSINESS_UNIT
AND H.WO_ID = A.WO_ID
AND H.WO_TASK_ID = A.WO_TASK_ID LEFT OUTER JOIN (
SELECT A.BUSINESS_UNIT
, A.WO_TASK_ID
, C.DESCR
, A.WO_ID
, C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A
, PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD = '08' ) I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT
AND I.WO_ID = A.WO_ID
AND I.WO_TASK_ID = A.WO_TASK_ID
WHERE ( A.ENS_TSK_CRT_VAL <> 0
AND A.WO_ID = '0000002151'
AND A.BUSINESS_UNIT = 'R3851' )
The case statements sometimes pick up the 'Y' and behave as expected, sometimes they don't. The fields being examined for 'Y' values are CHAR fields of one character in length. I've tried casting and converting to make certain that the value was what I was expecting in the case statement when compared to 'Y'. I've tried concatenating a '>' and '<' to either side to see if somehow there were whitespaces padding the value, and that was not the case at all. It just appears as though the case statement simply ceased working. Here is a small sample of what the data looked like, to give you an idea of what it was working with...sorry it's a little bit scrambled.
WO_TASK_ID WO_ID ENS_TSK_CRT_VAL ENS_TSK_CRT_V01 ENS_TSK_CRT_V02 ENS_TSK_CRT_V03
1 0000002151 2 Y N N
9 0000002151 12 N Y Y
12 0000002151 52 N Y N
I've since fixed the problem by taking a completely different route, but I just want to know how this is happening, and what to do to overcome the problem in the future when working with the CASE Expression again.
Any help is greatly appreciated...
Flynn

Possible this be helpful for you -
;WITH cte AS
(
SELECT A.BUSINESS_UNIT ,
A.WO_TASK_ID ,
C.DESCR ,
A.WO_ID ,
C.ENS_TSK_CRT_CD
FROM PS_ENS_WM_TSKCR_VW A ,
PS_ENS_WM_TSK_CRT C
WHERE A.ENS_TSK_CRT_V01 = 'Y'
AND C.SETID = 'SHARE'
AND C.ENS_TSK_CRT_CD IN (
'01', '02', '03', '04',
'05', '06', '07', '08'
)
)
SELECT A.BUSINESS_UNIT ,
A.WO_ID ,
A.WO_TASK_ID ,
A.ENS_TSK_CRT_VAL ,
ISNULL(B.DESCR, ' ') AS ENS_TSK_CRT_V01 ,
ISNULL(C.DESCR, ' ') AS ENS_TSK_CRT_V02 ,
ISNULL(D.DESCR, ' ') AS ENS_TSK_CRT_V03 ,
ISNULL(E.DESCR, ' ') AS ENS_TSK_CRT_V04 ,
ISNULL(F.DESCR, ' ') AS ENS_TSK_CRT_V05 ,
ISNULL(G.DESCR, ' ') AS ENS_TSK_CRT_V06 ,
ISNULL(H.DESCR, ' ') AS ENS_TSK_CRT_V07 ,
ISNULL(I.DESCR, ' ') AS ENS_TSK_CRT_V08
FROM PS_ENS_WM_TSKCR_VW A
LEFT JOIN cte B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT
AND B.WO_ID = A.WO_ID
AND B.WO_TASK_ID = A.WO_TASK_ID
AND B.ENS_TSK_CRT_CD = '01'
AND A.ENS_TSK_CRT_V01 = 'Y'
LEFT JOIN cte C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT
AND C.WO_ID = A.WO_ID
AND C.WO_TASK_ID = A.WO_TASK_ID
AND C.ENS_TSK_CRT_CD = '02'
AND A.ENS_TSK_CRT_V02 = 'Y'
LEFT JOIN cte D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT
AND D.WO_ID = A.WO_ID
AND D.WO_TASK_ID = A.WO_TASK_ID
AND D.ENS_TSK_CRT_CD = '03'
AND A.ENS_TSK_CRT_V03 = 'Y'
LEFT JOIN cte E ON E.BUSINESS_UNIT = A.BUSINESS_UNIT
AND E.WO_ID = A.WO_ID
AND E.WO_TASK_ID = A.WO_TASK_ID
AND E.ENS_TSK_CRT_CD = '04'
AND A.ENS_TSK_CRT_V04 = 'Y'
LEFT JOIN cte F ON F.BUSINESS_UNIT = A.BUSINESS_UNIT
AND F.WO_ID = A.WO_ID
AND F.WO_TASK_ID = A.WO_TASK_ID
AND F.ENS_TSK_CRT_CD = '05'
AND A.ENS_TSK_CRT_V05 = 'Y'
LEFT JOIN cte G ON G.BUSINESS_UNIT = A.BUSINESS_UNIT
AND G.WO_ID = A.WO_ID
AND G.WO_TASK_ID = A.WO_TASK_ID
AND G.ENS_TSK_CRT_CD = '06'
AND A.ENS_TSK_CRT_V06 = 'Y'
LEFT JOIN cte H ON H.BUSINESS_UNIT = A.BUSINESS_UNIT
AND H.WO_ID = A.WO_ID
AND H.WO_TASK_ID = A.WO_TASK_ID
AND H.ENS_TSK_CRT_CD = '07'
AND A.ENS_TSK_CRT_V07 = 'Y'
LEFT JOIN cte I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT
AND I.WO_ID = A.WO_ID
AND I.WO_TASK_ID = A.WO_TASK_ID
AND I.ENS_TSK_CRT_CD = '08'
AND A.ENS_TSK_CRT_V08 = 'Y'
WHERE A.ENS_TSK_CRT_VAL != 0
AND A.WO_ID = '0000002151'
AND A.BUSINESS_UNIT = 'R3851'

BTW, just in case anyone is curious, here was the workaround I used before posting my question about the CASE Expression to the original problem......
SELECT A.BUSINESS_UNIT , A.WO_ID , A.WO_TASK_ID , A.ENS_TSK_CRT_VAL
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,1) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 01 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL01
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,2) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 02 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL02
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,3) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 03 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL03
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,4) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 04 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL04
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,5) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 05 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL05
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,6) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 06 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL06
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,7) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 07 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL07
, (CASE WHEN (CASE WHEN CAST(A.ENS_TSK_CRT_VAL AS INT) & POWER(2,8) > 0 THEN 1 ELSE 0 END) = 1 THEN (SELECT DESCR FROM PS_ENS_WM_TSK_CRT WHERE ENS_TSK_CRT_CD = 08 AND SETID = 'SHARE') ELSE ' ' END) AS ENS_TSK_CRT_VAL08
FROM PS_ENS_WM_TSKCR_WO A
WHERE A.ENS_TSK_CRT_VAL <> 0
AND A.WO_ID = '0000002151' AND A.BUSINESS_UNIT = 'R3851'

I suspect it is the behavior of the case statement. I just discovered a difference in 2008 R2 vs 2005 and in my searches came upon your problem. Case is handled by sql server 2008 R2 differently than 2005. Note the statement in the remarks of the 2008 doc: "In some situations, an expression is evaluated before a CASE statement receives the results of the expression as its input. Errors in evaluating these expressions are possible."
So in 2008 all potential outputs may be evaluated even if not appropriate (the input doesn't evaluate to true), which is occuring in some stored procs of mine now after upgrading to 2008.
So perhaps in your case, regardless of whether B.DESCR, C.DESCR, D.DESCR, etc. equal 'Y',
B.DESCR, C.DESCR, D.DESCR, etc. get evaluated and may at that time be null or otherwise somehow unable to be compared to 'Y' thereby causing that part of the statement to fail (and this is silent it seems). Not sure but it smells the same as what I had for a problem. The only thing that makes me cautious about this "answer" is that my problem was within the where clause and yours is in the select part of the sql statement.
Regardless, maybe someone will find this helpful. It took some digging to figure this out.

you can try to remove trailing space from Y which can cause similar issues

Related

How can I sum the total based on a column in Firebird 2.5

How can get totalizations out of a group, especifically in Firebird 2.5.
I have the following query, it's big but it's simple, it has only some inner joins that are correlated.
SELECT "patrimônio", porc_residual AS "percentual residual", vida_util AS "vida útil",
vida_util_meses "vida útil meses", valor_base AS "valor aquisição/valor reavaliação",
"data de incorporação", VALOR_DEPRECIADO AS "valor depreciado" ,
grupo_audesp AS "grupo contábil", sum(dt_depreciado) over(ORDER BY grupo_audesp ) td
FROM
(
SELECT m.nome AS "patrimônio", t.PORC_RESIDUAL, t.VIDA_UTIL, t.VIDA_UTIL_MESES,
lpad(EXTRACT(DAY FROM t.dt_cadastro),2, '0') || '/' || lpad(EXTRACT(month FROM t.dt_cadastro),2, '0') || '/' || EXTRACT(year FROM t.dt_cadastro) "data de incorporação"
,t.placa, GA.ID_AUDESP, GA.NOME AS GRUPO_AUDESP,
T.VALOR as valor,
CASE WHEN (SELECT min(D.VALOR_NOVO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000' AND T.SITUACAO IN('A','B')
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) IS NULL THEN(
case when (select max(d.valor_anterior)
from patrimonio_depreciacao D where D.id_tombamento = T.id_tombamento and
T.SITUACAO IN('A','B')
AND d.referencia2 >202201 ) IS NULL THEN T.VALOR_ATUAL ELSE
(select max(d.valor_anterior)
from patrimonio_depreciacao D where D.id_tombamento = T.id_tombamento and
T.SITUACAO IN('A','B')
AND d.referencia2 >202201 )
END)
ELSE
(SELECT min(D.VALOR_NOVO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000' AND T.SITUACAO IN('A','B')
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) END as valor_atual,
(SELECT sum(D.VALOR_DEPRECIADO)
FROM patrimonio_depreciacao D WHERE D.id_tombamento = T.id_tombamento
AND T.ID_ORGAO = '030000'
AND D.REFERENCIA2 >=202201 AND D.REFERENCIA2 <=202201 ) as valor_depreciado, T.DT_AQUISICAO,
PS.NOME,
case when (select first 1 pri.vl_reavaliacao from patrimonio_reavaliacao_item pri
inner join patrimonio_reavaliacao pr on pr.id_reavaliacao = pri.id_reavaliacao_item
where pri.id_tombamento = t.id_tombamento
and pr.data<='2022-01-31'
and pr.encerrado ='S'
order by pr.data desc) is null then t.vl_base_depreciacao
else
(select first 1 pri.vl_reavaliacao from patrimonio_reavaliacao_item pri
inner join patrimonio_reavaliacao pr on pr.id_reavaliacao = pri.id_reavaliacao_item
where pri.id_tombamento = t.id_tombamento
and pr.data <= '2022-01-31'
and pr.encerrado ='S'
order by pr.data desc) end as valor_base
FROM PATRIMONIO_TOMBAMENTO T
LEFT JOIN PATRIMONIO_GRUPO_AUDESP GA ON GA.ID_GRUPO_AUDESP = T.ID_GRUPO_AUDESP
LEFT JOIN ESTOQUE_MATERIAL M ON M.ID_MATERIAL = T.ID_MATERIAL
LEFT JOIN PATRIMONIO_SETOR PS ON (T.ID_SETOR = PS.ID_SETOR)
WHERE T.ID_ORGAO = '030000'
AND (T.SITUACAO IN('A') or ( T.SITUACAO = 'B' AND T.DT_BAIXA >'2022-01-31'))
AND (T.DT_REATIVADO IS NULL OR T.DT_REATIVADO<= '2022-01-31' or (T.DT_BAIXA >'2022-01-31'))
AND T.dt_cadastro <= '2022-01-31'
AND PS.TIPO_SETOR = 'S'
ORDER BY GA.ID_AUDESP, t.DT_CADASTRO) t
I think most import is the result
I want to sum "valor depreciado" and "valor aquisição/valor reavaliação" based on those groups.
to make it simple it could be an additional column that repeats the sum in all rows for the entire group.

Invalid column in unpivot CTE query

I am getting the error Invalid column name MERCHANDISE_AMT'. on the below CTE unpivot query. I am selecting in MERCHANDISE_AMT in both queries so I do not understand why it's coming up as invalid. What am I overlooking here? If I take MERCHANDISE_AMT out of the unpivot than it runs, but I need to use this column for unpivoting. (unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
;WITH CTE AS (
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END AS LINE_TYPE , A.MERCHANDISE_AMT, CASE WHEN CONVERT(CHAR(24),A.QTY_VCHR) = '0' THEN '' ELSE B.QTY_VCHR END AS INVOICE_QTY, CASE WHEN CONVERT(CHAR(24),A.UNIT_PRICE) = '0' THEN '' ELSE A.UNIT_PRICE END AS UNIT_PRICE , A.UNIT_OF_MEASURE, REPLACE(A.DESCR,'"','') AS DESCR , '' AS BLANK1, '' AS BLANK2--A.PO_ID, A.LINE_NBR,
, ''AS BLANK3, ''AS BLANK4, --A.SCHED_NBR, B.PO_DIST_LINE_NUM,
''AS BLANK5,
''AS BLANK6,''AS BLANK7,''AS BLANK777,''AS BLANK8,''AS BLANK9,''AS BLANK10,''AS BLANK11,''AS BLANK12,
F.ORACLE_ENTITY + '.' + F.ORACLE_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '881' THEN '000'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '889' THEN '950'
WHEN B.BUSINESS_UNIT_GL = '11000' AND H.DEPTID = '775' THEN '000'
WHEN B.DEPTID = '' THEN '000'
ELSE B.DEPTID END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000.' + '000000' AS SEGMENTS ,
''AS BLANK13, '2021/05/31' AS DATE1, ''AS BLANK14,''AS BLANK15,''AS BLANK16,''AS BLANK17, ''AS BLANK18, --A.SHIPTO_ID
''AS BLANK19,''AS BLANK199,''AS BLANK1999,''AS BLANK20,''AS BLANK21,''AS BLANK211,''AS BLANK22,''AS BLANK23,''AS BLANK24,''AS BLANK25,''AS BLANK26,''AS BLANK27,''AS BLANK28,''AS BLANK29,''AS BLANK30,''AS BLANK31,
''AS BLANK134,
''AS BLANK32, ''AS BLANK33, ''AS BLANK34, --A.SALETX_AMT --<--IS THIS THE RIGHT FIELD?
''AS BLANK35, ''AS BLANK36, --B.QTY_VCHR,
'N'AS BLANK37, ''AS BLANK38,''AS BLANK39,''AS BLANK40,''AS BLANK41,''AS BLANK411,''AS BLANK42, ''AS BLANK43, ''AS BLANK44,''AS BLANK45,''AS BLANK46,''AS BLANK47,''AS BLANK48,''AS BLANK49,''AS BLANK50,''AS BLANK51,''AS BLANK52,''AS BLANK53,''AS BLANK54,''AS BLANK55,''AS BLANK56,''AS BLANK57,''AS BLANK58,''AS BLANK59,''AS BLANK60,''AS BLANK61,''AS BLANK62,''AS BLANK63,''AS BLANK64,''AS BLANK65,''AS BLANK66,''AS BLANK67,''AS BLANK68,''AS BLANK69,''AS BLANK70,''AS BLANK71,''AS BLANK72,''AS BLANK73,''AS BLANK74,''AS BLANK75,''AS BLANK76,''AS BLANK77,''AS BLANK78,''AS BLANK79,''AS BLANK80,
''AS BLANK81,''AS BLANK82,''AS BLANK83,''AS BLANK84,''AS BLANK85,''AS BLANK86,''AS BLANK87,''AS BLANK88,''AS BLANK89,''AS BLANK90,''AS BLANK91,''AS BLANK92,''AS BLANK93,''AS BLANK94,''AS BLANK95,''AS BLANK96,''AS BLANK97,''AS BLANK98,''AS BLANK99,''AS BLANK100,''AS BLANK101,''AS BLANK102,''AS BLANK103,''AS BLANK104,''AS BLANK105,''AS BLANK106,''AS BLANK107,''AS BLANK108,''AS BLANK109,''AS BLANK110,''AS BLANK111,''AS BLANK112,''AS BLANK113,''AS BLANK114,''AS BLANK115,''AS BLANK116,''AS BLANK117,''AS BLANK118,''AS BLANK119,''AS BLANK120,''AS BLANK121,''AS BLANK122,''AS BLANK123,''AS BLANK124,''AS BLANK125,''AS BLANK126,''AS BLANK127,''AS BLANK128,''AS BLANK129,''AS BLANK130,''AS BLANK131,'' AS BLANK132
, C.SALETX_AMT, C.FREIGHT_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM AND D.WTHD_ENTITY = 'IRS'
LEFT OUTER JOIN PS_VCHR_LINE_WTHD DD ON DD.BUSINESS_UNIT = D.BUSINESS_UNIT AND DD.VOUCHER_ID = D.VOUCHER_ID AND DD.VOUCHER_LINE_NUM = D.VOUCHER_LINE_NUM AND DD.WTHD_ENTITY = 'PA'
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND C.ACCOUNTING_DT < '06-01-2021'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
AND C.MATCH_STATUS_VCHR = 'M'
AND C.APPR_STATUS = 'A'
AND B.VOUCHER_ID = '00720667' )
SELECT INVOICE_ID, VOUCHER_LINE_NUM - 1 + row_number() over (PARTITION BY INVOICE_ID, VOUCHER_LINE_NUM ORDER BY VOUCHER_LINE_NUM) AS VOUCHER_LINE_NUM,
LINE_TYPE, MERCHANDISE_AMT, INVOICE_QTY, UNIT_PRICE, UNIT_OF_MEASURE, DESCR , BLANK1, BLANK2--A.PO_ID, A.LINE_NBR,
, BLANK3, BLANK4,
BLANK5, BLANK6,BLANK7,BLANK777,BLANK8,BLANK9,BLANK10,BLANK11,BLANK12,
SEGMENTS, BLANK13, DATE1, BLANK14,BLANK15,BLANK16,BLANK17, BLANK18,
BLANK19,BLANK199,BLANK1999,BLANK20,BLANK21,BLANK211,BLANK22,BLANK23,BLANK24,BLANK25,BLANK26,BLANK27,BLANK28,
BLANK29,BLANK30,BLANK31,
BLANK133,
BLANK134, BLANK32, BLANK33, BLANK34,
BLANK35, BLANK36,
BLANK37, BLANK38,BLANK39,BLANK40,BLANK41,BLANK411,BLANK42, BLANK43, BLANK44,BLANK45,BLANK46,BLANK47,BLANK48,BLANK49,BLANK50,BLANK51,BLANK52,BLANK53,BLANK54,BLANK55,BLANK56,BLANK57,BLANK58,BLANK59,BLANK60,BLANK61,BLANK62,BLANK63,BLANK64,BLANK65,BLANK66,BLANK67,BLANK68,BLANK69,BLANK70,BLANK71,BLANK72,BLANK73,BLANK74,BLANK75,BLANK76,BLANK77,BLANK78,BLANK79,BLANK80,
BLANK81,BLANK82,BLANK83,BLANK84,BLANK85,BLANK86,BLANK87,BLANK88,BLANK89,BLANK90,BLANK91,BLANK92,BLANK93,BLANK94,BLANK95,BLANK96,BLANK97,BLANK98,BLANK99,BLANK100,BLANK101,BLANK102,BLANK103,BLANK104,BLANK105,BLANK106,BLANK107,BLANK108,BLANK109,BLANK110,BLANK111,BLANK112,BLANK113,BLANK114,BLANK115,BLANK116,BLANK117,BLANK118,BLANK119,BLANK120,BLANK121,BLANK122,BLANK123,BLANK124,BLANK125,BLANK126,BLANK127,BLANK128,BLANK129,BLANK130,BLANK131,BLANK132 , value
FROM CTE
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
WHERE value > 0.00
You cannot include MERCHANDISE_AMT here:
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)
AND in your final SELECT from the UNPIVOT results (4th column result set).
Including it in the IN list here means that you are unpivoting the value of this column into your row structure, so you can no longer select its value in your final SELECT.
So you need to pick. Do you want to unpivot the values in MERCHANDISE_AMT? If so, then leave it in the IN list of your UNPIVOT and remove it from final SELECT. If not, then remove it from your IN list and leave it in your final SELECT.
Seems like you would likely benefit from reading through the Microsoft examples on UNPIVOT.

Wrap CTE inside another Select statement

Is it possible to wrap a CTE inside of another Select statement?
Here is my CTE:
WITH IRS AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'IRS' ) ,
PA AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'PA' )
SELECT IRS_WTHD.BUSINESS_UNIT, IRS_WTHD.VOUCHER_ID, IRS_WTHD.VOUCHER_LINE_NUM,
--COLUMN 1 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN 'PA'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'IRS'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'IRS'
ELSE ''
END ,
--COLUMN 2 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ','0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'MISC7'
WHEN PA_WTHD.WTHD_ENTITY = '' THEN ''
ELSE 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
END
FROM IRS IRS_WTHD
LEFT JOIN PA PA_WTHD ON PA_WTHD.BUSINESS_UNIT = IRS_WTHD.BUSINESS_UNIT AND PA_WTHD.VOUCHER_ID = IRS_WTHD.VOUCHER_ID AND PA_WTHD.VOUCHER_LINE_NUM = IRS_WTHD.VOUCHER_LINE_NUM
I would like to wrap the above CTE inside of this main SQL Select statement below and output the two CASE statement columns above into the final SELECT statement below while joining on BUSINESS_UNIT, VOUCHER_ID, and VOUCHER_LINE_NUM fields from the PS_VCHR_LINE_WTHD table :
--Main Select Statement:
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END, A.MERCHANDISE_AMT, B.QTY_VCHR, A.UNIT_PRICE, A.UNIT_OF_MEASURE, A.DESCR, A.PO_ID, A.LINE_NBR,
A.SCHED_NBR, B.PO_DIST_LINE_NUM, A.DESCR254_MIXED, '','',
F.OR_ENTITY + '.' + F.OR_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
ELSE '000' END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000000.' + '000000' ,'', C.ACCOUNTING_DT, '',
'','','', ISNULL(D.WTHD_ENTITY,''), '', '', '', A.SALETX_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
ORDER BY 1,2
Is this possible, or is there an alternate way of avoiding using the CTE? I am using the CTE because I need to be able to run Case statements across multiple rows and possibly return data on other rows.

The multi-part identifier could not be bound sql error

I have taken over the support of an Excel 2010 macro and need to change the sort order of a recordset.
The query below worked before I attempted to change the order by adding rl.list_order.
Now I'm getting the error "The multi-part identifier could not be bound" and have tried many alternatives and have researched on this site for a solution but haven't been able to solve this. Can someone please help.
SELECT ips_rc.project, lfbe.Category, ips_rc.roster_id, ips_rc.role_category, ips_rc.role_title AS Role, ips_rc.role_code, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role, CASE WHEN ISNULL(lfbe.Pronto_Role_Code, '') = '' THEN 'TO_BE_MAPPED' ELSE ISNULL(lfbe.Pronto_Role_Code, '') END AS Pronto_Role_Code, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = '' THEN ips_rc.role_title ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '') END AS Pronto_Role_Code_Description, ISNULL(lfbe.Rate, 0) AS Rate, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = '' THEN ips_rc.role_title ELSE lfbe.Pronto_Role_Code_Old END AS Pronto_Role_Code_Old, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = '' THEN 'TO_BE_MAPPED' ELSE lfbe.Pronto_Role_Code_Description_Old END AS Pronto_Role_Code_Description_Old, ips_rc.Shift, ips_rc.UOM, ips_rc.Date, ips_rc.DHours, ips_rc.NHours FROM (SELECT psrc.project, pr_jcm.customer, pr_jcm.subcode, psrc.roster_id, psrc.role_id, psrc.role_category, psrc.role_title,
psrc.role_code, CASE WHEN SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.NWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.DWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) THEN 'Night Shifts' ELSE 'Day Shifts' END AS Shift, 'HOURS' AS UOM, psrc.Date, psrc.DHours, psrc.NHours FROM (SELECT rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id AS role_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END AS role_category, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END AS role_title, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_r
ole_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END AS role_code, rcd.shift_date AS Date, SUM(CASE WHEN rcd.shift_ampm = 'day' THEN rcd.shift_time ELSE 0 END) AS DHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS DWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS DEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS DEqdemobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' THEN rcd.shift_time ELSE 0 END) AS NHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS NWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS NEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.sh
ift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS NEqdemobHours FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_r
ole_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')) AS rb_test1 ON rb_test1.client_id = rcd.client_id AND rb_test1.role1_id = rcd.role1_id AND rb_test1.role2_id = rcd.role2_id AND rb_test1.role3_id = rcd.role3_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id '
)) AS rb_test2 ON rb_test2.client_id = rcd.client_id AND rb_test2.role1_id = rcd.role1_id AND rb_test2.role2_id = rcd.role2_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')) AS rb_test3 ON rb_test3.client_id = rcd.client_id AND rb_test3.role1_id = rcd.role1_id AND rb_test3.role3_id = rcd.role3_id WHERE rcd.shift_date > '2017-01-01' GROUP BY rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role
1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_role_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END, rcd.shift_date) AS psrc INNER JOIN (SELECT job_no AS project, Client AS customer, '3700002213' AS subcode FROM [dbo].[vw_PlanningSystem_Projects] WHERE job_no = '700704') AS pr_jcm ON pr_jcm.project = psrc.project) AS ips_rc LEFT OUTER JOIN (SELECT rates.Client, rates.SubCode, mapping.Category, mapping.Shift, mapping.IPS_Role_Code, rates.Pronto_Role_Code, rates.Pronto_Role_Code_Description, rates.Rate, rates.Pronto_Role_Code_Old, rates.Pronto_Role_Code_Description_Old FROM (SELECT UPPER(Ca
tegory) AS Category, 'Day Shifts' AS Shift, IPS_Role_Code, Day_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping] UNION ALL SELECT UPPER(Category) AS Category, 'Night Shifts' AS Shift, IPS_Role_Code, Night_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]) AS mapping INNER JOIN (SELECT Client, SubCode, CASE WHEN Shift = 'Day Shift' THEN 'Day Shifts' WHEN Shift = 'Night Shift' THEN 'Night Shifts' Else '' END AS Shift, Pronto_Role_Code, Pronto_Role_Code_Description, Rate, Pronto_Role_Code_Old, Pronto_Role_Code_Description_Old FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]) AS rates ON rates.Shift = mapping.Shift AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code) AS lfbe ON lfbe.Client = ips_rc.customer AND lfbe.SubCode = ips_rc.subCode AND lfbe.Shift = ips_rc.Shift AND lfbe.IPS_Role_Code = ips_rc.role_code ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, rl.list_order
Thanks for your help
Even with the formatting, you've got a lot going on here... Stack Overflow veterans, I'm just starting to dip my toes in here, so if this isn't correct, give me some grace.
In your first OPENQUERY statement, I don't see rl.list_order as a field being returned. If that's a column you're trying to ORDER BY, I think you should be able to add rl.list_order to your SELECT list within that statement which you alias as rcd.
Since that's within a nested sub-query, you'll want to elevate it to each of the calling queries. I think it's something like this... Try it out and post back with any errors.
SELECT ips_rc.ListOrder
, ips_rc.project
, lfbe.Category
, ips_rc.roster_id
, ips_rc.role_category
, ips_rc.role_title AS [ROLE]
, ips_rc.role_code
, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code, '') = ''
THEN 'TO_BE_MAPPED'
ELSE ISNULL(lfbe.Pronto_Role_Code, '')
END AS Pronto_Role_Code
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = ''
THEN ips_rc.role_title
ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '')
END AS Pronto_Role_Code_Description
, ISNULL(lfbe.Rate, 0) AS Rate
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = ''
THEN ips_rc.role_title
ELSE lfbe.Pronto_Role_Code_Old
END AS Pronto_Role_Code_Old
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = ''
THEN 'TO_BE_MAPPED'
ELSE lfbe.Pronto_Role_Code_Description_Old
END AS Pronto_Role_Code_Description_Old
, ips_rc.Shift
, ips_rc.UOM
, ips_rc.DATE
, ips_rc.DHours
, ips_rc.NHours
FROM (
SELECT psrc.ListOrder -- Added
, psrc.project
, pr_jcm.customer
, pr_jcm.subcode
, psrc.roster_id
, psrc.role_id
, psrc.role_category
, psrc.role_title
, psrc.role_code
, CASE
WHEN SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.NWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.DWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id)
THEN 'Night Shifts'
ELSE 'Day Shifts'
END AS Shift, 'HOURS' AS UOM, psrc.DATE, psrc.DHours, psrc.NHours
FROM (
SELECT rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id AS role_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END AS role_category
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END AS role_title
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END AS role_code, rcd.shift_date AS DATE
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
THEN rcd.shift_time
ELSE 0
END) AS DHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS DWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS DEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS DEqdemobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
THEN rcd.shift_time
ELSE 0
END) AS NHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS NWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS NEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS NEqdemobHours
FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl,ListOrder, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd --Added
LEFT JOIN (
SELECT client_id
, band_role_id
, title
, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category
, role1_id
, role2_id
, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')
) AS rb_test1
ON rb_test1.client_id = rcd.client_id
AND rb_test1.role1_id = rcd.role1_id
AND rb_test1.role2_id = rcd.role2_id
AND rb_test1.role3_id = rcd.role3_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role2_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id ')
) AS rb_test2
ON rb_test2.client_id = rcd.client_id
AND rb_test2.role1_id = rcd.role1_id
AND rb_test2.role2_id = rcd.role2_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')
) AS rb_test3
ON rb_test3.client_id = rcd.client_id
AND rb_test3.role1_id = rcd.role1_id
AND rb_test3.role3_id = rcd.role3_id
WHERE rcd.shift_date > '2017-01-01'
GROUP BY rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.ROLE1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END
, rcd.shift_date
) AS psrc
INNER JOIN (
SELECT job_no AS project
, Client AS customer
, '3700002213' AS subcode
FROM [dbo].[vw_PlanningSystem_Projects]
WHERE job_no = '700704'
) AS pr_jcm
ON pr_jcm.project = psrc.project
) AS ips_rc
LEFT JOIN (
SELECT rates.Client
, rates.SubCode
, mapping.Category
, mapping.Shift
, mapping.IPS_Role_Code
, rates.Pronto_Role_Code
, rates.Pronto_Role_Code_Description
, rates.Rate
, rates.Pronto_Role_Code_Old
, rates.Pronto_Role_Code_Description_Old
FROM (
SELECT UPPER(Category) AS Category
, 'Day Shifts' AS Shift
, IPS_Role_Code
, Day_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
UNION ALL
SELECT UPPER(Category) AS Category
, 'Night Shifts' AS Shift
, IPS_Role_Code
, Night_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
) AS mapping
INNER JOIN (
SELECT Client
, SubCode
, CASE
WHEN Shift = 'Day Shift'
THEN 'Day Shifts'
WHEN Shift = 'Night Shift'
THEN 'Night Shifts'
ELSE ''
END AS Shift
, Pronto_Role_Code
, Pronto_Role_Code_Description
, Rate
, Pronto_Role_Code_Old
, Pronto_Role_Code_Description_Old
FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]
) AS rates
ON rates.Shift = mapping.Shift
AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code
) AS lfbe
ON lfbe.Client = ips_rc.customer
AND lfbe.SubCode = ips_rc.subCode
AND lfbe.Shift = ips_rc.Shift
AND lfbe.IPS_Role_Code = ips_rc.role_code
ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, ips_rc.list_order ASC
You're right CSharp821 there's an awful lot going on there. I made the changes you suggested and it now works!
You are trying to access alias rl, however the rl alias is only visible within the OPENQUERY which has an alias of rcd. Try order by rcd.list_order instead of rl.list_order

several select counts in select could be enhanced?

I have the below query , If the table data grows and contained millions of record , would it cause performance issue ? can it be enhanced in a way I dont run select count() in the select several time ? I already added index on the 6 columns.
I know the join is bad I am already enhancing the query
SELECT
P.CID,
P.CB,
(SELECT COUNT(1)
FROM EED_TABLE F
WHERE F.ID = P.ID
AND F.BC = P.BC
AND F.PCD = P.PCD
AND F.CID = P.CID
AND F.BRC = P.BRC
AND F.ST = 'F') ST_F,
(SELECT COUNT(1)
FROM EED_TABLE N
WHERE N.ID = P.ID
AND N.BC = P.BC
AND N.PCD = P.PCD
AND N.COMP_CODE = P.COMP_CODE
AND N.BRC = P.BRC
AND N.ST = 'N') ST_N,
(SELECT COUNT(1)
FROM EED_TABLE A
WHERE A.ID = P.ID
AND A.BC = P.BC
AND A.PCD = P.PCD
AND A.CID = P.CID
AND F.BRC = P.BRC
AND A.ST = 'A') ST_A
FROM EED_TABLE P ,EDD_DEF D
WHERE P.PCD = D.PCD
AND P.BC= D.BC
AND P.CD= 1
AND P.ID = 1
AND P.BC= 22
AND P.PCD = 31
I always prefer to go for JOIN instead of having more select statements, this is how I would do it, not knowing your data of course so maybe it won't work, but give it a shot and let me know of results and speed
select
p.cid, p.cb, SUM(case when f.id is not null then 1 else 0 end) st_f,
, SUM(case when a.id is not null then 1 else 0 end) st_a
, SUM(case when n.id is not null then 1 else 0 end) st_n
from eed_table p
join edd_def d on p.pcd = d.pcd and p.bc = d.bc
left join eed_table f on f.id = p.id and f.bc = p.bc
and f.pcd = p.pcd and f.cid = p.cid
and f.brc = p.brc and f.st = 'f'
left join eed_table a on p.id = a.id and p.bc = a.bc
and p.pcd = a.pcd and p.cid = a.cid
and p.brc = a.brc and a.st = 'a'
left join eed_table n on n.id = p.id and n.bc = p.bc
and n.pcd = p.pcd and n.comp_code = p.comp_code
and n.brc = p.brc and n.st = 'n'
where p.cd = 1 and p.id = 1 and p.bc = 22 and p.pcd = 31
group by p.cid, p.cb
Seems that your query can be rewritten with window functions as:
SELECT
DISTINCT P.CID, P.CB
, SUM(CASE WHEN P.ST = 'F' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.CID, P.BRC) ST_F
, SUM(CASE WHEN P.ST = 'N' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.COMP_CODE, P.BRC) ST_N
, SUM(CASE WHEN P.ST = 'A' THEN 1 ELSE 0 END) OVER (PARTITION BY P.ID, P.BC, P.PCD, P.CID, P.BRC) ST_A
FROM
EED_TABLE P
WHERE
P.CD = 1
AND P.ID = 1
AND P.BC = 22
AND P.PCD = 31
AND EXISTS (SELECT 1 FROM EDD_DEF D WHERE P.PCD = D.PCD AND P.BC= D.BC)