Invalid column in unpivot CTE query - sql

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.

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.

How to group by two columns in different CASE clauses

I have a query that's giving me the results I want, but for each item with a given ID_UNIDAD_EXPERIMENTAL there are two rows, one with column "Alt" with a value and column "Dap" with null, and the other one with "Alt" null and "Dap" with a value.
My question is: How can I group them so each element with a given ID just shows both Alt and Dap columns with values, kind of "removing" the nulls.
Heres the query:
SELECT ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('alt') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as alt,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('dap') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as dap
FROM ENS_Medicion
JOIN ENS_Variable_medicion ON ENS_Variable_medicion.id_variable_medicion = ENS_Medicion.id_variable_med
JOIN Variable_simple ON Variable_simple.id_variable_simple = ENS_Variable_medicion.id_variable_simple
join ENS_Variable_medicion varmed on ENS_Medicion.id_variable_med = varmed.id_variable_medicion
join Variable_simple vs on varmed.id_variable_simple = vs.id_variable_simple
join ENS_Medicion_resumen mr on mr.id_medicion_resumen = ENS_Medicion.id_medicion_resumen
where mr.nro_medicion = 3 and mr.id_ensayo = 9227 and (UPPER(Variable_simple.nombre) = UPPER('alt') or UPPER(Variable_simple.nombre) = UPPER('dap'))
GROUP BY ENS_Medicion.id_medicion_resumen, ENS_Medicion.id_unidad_exprimental, Variable_simple.nombre, valor_medido, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental
ORDER BY id_unidad_exprimental
and here are the results:
you can see that there are two rows for each "id_unidad_experimental" and each row has one column with a null value, the goal is to only show one row for "id_unidad_experimental" with the two values.
Any help would be nice
Try it like:
WITH cte as(
SELECT ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('alt') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as alt,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('dap') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as dap
FROM ENS_Medicion
JOIN ENS_Variable_medicion ON ENS_Variable_medicion.id_variable_medicion = ENS_Medicion.id_variable_med
JOIN Variable_simple ON Variable_simple.id_variable_simple = ENS_Variable_medicion.id_variable_simple
join ENS_Variable_medicion varmed on ENS_Medicion.id_variable_med = varmed.id_variable_medicion
join Variable_simple vs on varmed.id_variable_simple = vs.id_variable_simple
join ENS_Medicion_resumen mr on mr.id_medicion_resumen = ENS_Medicion.id_medicion_resumen
where mr.nro_medicion = 3 and mr.id_ensayo = 9227 and (UPPER(Variable_simple.nombre) = UPPER('alt') or UPPER(Variable_simple.nombre) = UPPER('dap'))
GROUP BY ENS_Medicion.id_medicion_resumen, ENS_Medicion.id_unidad_exprimental, Variable_simple.nombre, valor_medido, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental
ORDER BY id_unidad_exprimental)
select t1.id_medicion_resumen, t1.id_ensayo, t1.id_unidad_exprimental, t1.alt, t2.dap
from cte t1
inner join cte t2 on t1.id_medicion_resumen = t2.id_medicion_resumen and t1.id_ensayo = t2.id_ensayo and t1.id_unidad_exprimental = t2.id_unidad_exprimental
where t1.alt is not null
and t2.dap is not null
Try this. I used derived table of your result to get the output. But unfortunately I cannot test the result. Better if you can give some sample data.
SELECT DISTINCT A.id_medicion_resumen
, A.id_ensayo
, A.id_unidad_exprimental
, MAX(alt) OVER ( Partition BY A.id_unidad_exprimental ORDER BY A.id_medicion_resumen) AS Alt
, MAX(dap) OVER ( Partition BY A.id_unidad_exprimental ORDER BY A.id_medicion_resumen) AS DAP
FROM
(
SELECT ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('alt') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as alt,
CASE WHEN UPPER(Variable_simple.nombre) = UPPER('dap') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END as dap
FROM ENS_Medicion
JOIN ENS_Variable_medicion ON ENS_Variable_medicion.id_variable_medicion = ENS_Medicion.id_variable_med
JOIN Variable_simple ON Variable_simple.id_variable_simple = ENS_Variable_medicion.id_variable_simple
join ENS_Variable_medicion varmed on ENS_Medicion.id_variable_med = varmed.id_variable_medicion
join Variable_simple vs on varmed.id_variable_simple = vs.id_variable_simple
join ENS_Medicion_resumen mr on mr.id_medicion_resumen = ENS_Medicion.id_medicion_resumen
where mr.nro_medicion = 3 and mr.id_ensayo = 9227 and (UPPER(Variable_simple.nombre) = UPPER('alt') or UPPER(Variable_simple.nombre) = UPPER('dap'))
GROUP BY ENS_Medicion.id_medicion_resumen, ENS_Medicion.id_unidad_exprimental, Variable_simple.nombre, valor_medido, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental
ORDER BY id_unidad_exprimental
) AS A
Use aggregation functions and fix the GROUP BY:
SELECT ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental,
MAX(CASE WHEN UPPER(Variable_simple.nombre) = UPPER('alt') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END) as alt,
MAX(CASE WHEN UPPER(Variable_simple.nombre) = UPPER('dap') THEN CONVERT(decimal(18,7), ISNULL(NULLIF(valor_medido, ''), '0')) END) as dap
. . .
GROUP BY ENS_Medicion.id_medicion_resumen, mr.id_ensayo, ENS_Medicion.id_unidad_exprimental

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.

Connecting Tableau to Teradata with Custom SQL Query

EDIT: Even if I try removing that 'AS' everywhere, I continue getting errors about things that seem like normal SQL commands. If I remove the 'AS', the next error I get is:
[IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "CAST"
following "" is not valid. Expected tokens may include: ", )".
SQLSTATE=42601
Question:
I am trying to connect to Teradata with a Custom SQL Query, and while it is running perfectly in Teradata SQL Assistant, I keep getting errors when trying to run it in Tableau.
One of the errors looks like this, but even if I try to change something, a similar error will come up:
[IBM][CLI Driver][DB2] SQL0199N The use of the reserved word "AS"
following "" is not valid. Expected tokens may include: "JOIN CROSS
INNER LEFT RIGHT FULL (". SQLSTATE=42601
Here is the query (sorry, it's long):
WITH RQSTS AS(
select CAST( M.RQST_ID AS VARCHAR(20)) AS MASTER_RQST_ID,
M.RQST_TYP_CD
FROM PRTHD.HOST_RQST AS M --MASTER
WHERE M.MSTR_RQST_ID IS NULL
AND M.crt_user_id='SXB8NBS'
AND M.OCYC_SOQ_RSN_CD = 170
AND date(M.CRT_TS) >= CURRENT_DATE - 7 DAY
),
RQST_TYPE AS(
select R.MASTER_RQST_ID AS RQST_ID,
NRT.TYP_DESC AS HOST_TYPE
FROM RQSTS AS R
LEFT JOIN PRTHD.N_HOST_RQST_TYP AS NRT
ON R.RQST_TYP_CD = NRT.RQST_TYP_CD
GROUP BY R.MASTER_RQST_ID, NRT.TYP_DESC
),
PO_DETAILS AS(
select A.*
FROM (
SELECT distinct PRTHD.BYO_PO.DSVC_TYP_CD,
RT.RQST_ID,
RT.HOST_TYPE,
PRTHD.BYO_PO.PO_CMT_TXT,
PRTHD.BYO_PO.BYO_NBR,
CASE WHEN PRTHD.BYO_PO.DSVC_TYP_CD = 2 THEN RIGHT('00'||PRTHD.BYO_PO.BYO_NBR,2)
ELSE RIGHT('00'|| PRTHD.BYO_PO_LOC_SKU.LOC_NBR,2) END
|| PRTHD.BYO_PO.acct_po_typ_cd || RIGHT('00000'||PRTHD.BYO_PO.PO_CTRL_NBR,5) AS PO,
PRTHD.BYO_PO.ORD_REF_NBR,
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR,
PRTHD.BYO_PO_LOC_SKU.LOC_NBR,
PRTHD.BYO_PO_LOC_SKU.SKU_NBR,
CAST(PRTHD.BYO_PO_LOC_SKU.ORD_QTY AS INTEGER) AS ORD_QTY,
PRTHD.BYO_PO.CRT_DT,
PRTHD.BYO_PO.PO_CTRL_NBR,
M.MVNDR_NM,
PRTHD.BYO_PO.MVNDR_NBR,
PRTHD.BYO_PO.OCYC_SOQ_RSN_CD AS RSN_CD
FROM ((PRTHD.BYO_PO AS BP INNER JOIN PRTHD.BYO_PO_LOC_SKU
ON (PRTHD.BYO_PO.ORD_SEQ_NBR = PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR)
AND (PRTHD.BYO_PO.PO_CTRL_NBR = PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR)
AND (PRTHD.BYO_PO.ACCT_PO_TYP_CD = PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD)
AND (PRTHD.BYO_PO.MKT_DC_NBR = PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR)
AND (PRTHD.BYO_PO.MKT_DC_IND = PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND)
AND (PRTHD.BYO_PO.BYO_NBR = PRTHD.BYO_PO_LOC_SKU.BYO_NBR))
INNER JOIN PRTHD.SKU
ON PRTHD.BYO_PO_LOC_SKU.SKU_NBR = PRTHD.SKU.SKU_NBR)
INNER JOIN PRTHD.BYO_PO_SKU
ON (PRTHD.SKU.SKU_NBR = PRTHD.BYO_PO_SKU.SKU_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.BYO_NBR = PRTHD.BYO_PO_SKU.BYO_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND = PRTHD.BYO_PO_SKU.MKT_DC_IND)
AND (PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR = PRTHD.BYO_PO_SKU.MKT_DC_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD = PRTHD.BYO_PO_SKU.ACCT_PO_TYP_CD)
AND (PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR = PRTHD.BYO_PO_SKU.PO_CTRL_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR = PRTHD.BYO_PO_SKU.ORD_SEQ_NBR)
AND (PRTHD.BYO_PO_LOC_SKU.PO_LINE_NBR = PRTHD.BYO_PO_SKU.PO_LINE_NBR)
LEFT JOIN PRTHD.MVNDR AS M
ON M.MVNDR_NBR = PRTHD.BYO_PO.MVNDR_NBR
INNER JOIN RQST_TYPE AS RT
ON TRIM(SUBSTR(BP.PO_CMT_TXT,6,11)) = RT.RQST_ID
) AS A)
Select P.RQST_ID,
P.DSVC_TYP_CD,
CASE WHEN P.DSVC_TYP_CD =1 THEN 'DTS'
WHEN P.DSVC_TYP_CD =2 THEN 'RDC AGG'
WHEN P.DSVC_TYP_CD =3 THEN 'RDCX'
END AS DSVC_TYP_DESC ,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN 'Y'
ELSE 'N' END AS RDC_AGG_PEG_FLG,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN P.ORD_REF_NBR
ELSE P.PO END AS PO_NBR,
P.BYO_NBR,
P.PO_CTRL_NBR,
P.CRT_DT,
P.HOST_TYPE,
P.MVNDR_NBR,
P.MVNDR_NM,
CASE WHEN P.DSVC_TYP_CD =2 AND S.STR_NBR IS NOT NULL THEN AR.MKT_DC_NBR
ELSE P.MKT_DC_NBR END AS MKT_DC_NBR,
P.LOC_NBR,
COALESCE(SKU.MER_DEPT_NBR || '-' || D.SHRT_DEPT_NM,'') AS DEPT,
COALESCE(SKU.MER_CLASS_NBR || '-' || MC.SHRT_CLASS_DESC,'') AS CLASS,
COALESCE(SKU.MER_SUB_CLASS_NBR || '-' || MSC.SHRT_SUBCLASS_DESC,'') AS SUB_CLASS,
P.SKU_NBR,
P.ORD_QTY,
COALESCE(SD.AVG_DC_LCOST_AMT*COALESCE(P.ORD_QTY,0),
MSM.CURR_COST_AMT*COALESCE(P.ORD_QTY,0)) AS TOTAL_COST,
SD.AVG_DC_LCOST_AMT AS SD_COST,
MSM.CURR_COST_AMT AS STR_CURR_COST,
MSD.CURR_COST_AMT AS DC_CURR_COST,
P.PO_CMT_TXT,
P.RSN_CD
FROM PO_DETAILS AS P
--SKU HIERARCHY INFO
LEFT JOIN PRTHD.SKU AS SKU
ON SKU.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.DEPT AS D
ON SKU.MER_DEPT_NBR = D.DEPT_NBR
LEFT JOIN PRTHD.MER_CLASS AS MC
ON MC.MER_DEPT_NBR= SKU.MER_DEPT_NBR
AND MC.MER_CLASS_NBR = SKU.MER_CLASS_NBR
LEFT JOIN PRTHD.MER_SUB_CLASS AS MSC
ON MSC.MER_DEPT_NBR= SKU.MER_DEPT_NBR
AND MSC.MER_CLASS_NBR = SKU.MER_CLASS_NBR
AND MSC.MER_SUB_CLASS_NBR = SKU.MER_SUB_CLASS_NBR
LEFT JOIN PRTHD.MVNDR_SKU_DC AS MSD
ON MSD.MVNDR_NBR = P.MVNDR_NBR
AND MSD.SKU_NBR = P.SKU_NBR
AND MSD.DC_NBR = P.LOC_NBR
LEFT JOIN PRTHD.STR AS S
ON S.STR_NBR = P.LOC_NBR
LEFT JOIN PRTHD.SKU_DC AS SD
ON SD.DC_NBR=P.MKT_DC_NBR
AND SD.SKU_NBR=P.SKU_NBR
LEFT JOIN PRTHD.MVNDR_SKU_MKT AS MSM
ON MSM.MVNDR_NBR = P.MVNDR_NBR
AND MSM.SKU_NBR = P.SKU_NBR
AND MSM.MKT_NBR = S.MKT_NBR
LEFT JOIN PRTHD.AGG_RQST AS AR
ON AR.PO_NBR = P.ORD_REF_NBR
AND P.MVNDR_NBR = AR.MVNDR_NBR
AND SKU.MER_DEPT_NBR = AR.MER_DEPT_NBR
AND AR.ORD_DT >= P.CRT_DT
Can anyone help me figure out what might be going wrong here? Thank you!
Delete all the AS:
WITH RQSTS (
select CT(M.RQST_ID VARCHAR(20)) MTER_RQST_ID,
M.RQST_TYP_CD
FROM PRTHD.HOST_RQST M --MTER
WHERE M.MSTR_RQST_ID IS NULL
AND M.crt_user_id = 'SXB8NBS'
AND M.OCYC_SOQ_RSN_CD = 170
AND date(M.CRT_TS) >= CURRENT_DATE - 7 DAY
),
RQST_TYPE (
select R.MTER_RQST_ID RQST_ID,
NRT.TYP_DESC HOST_TYPE
FROM RQSTS R
LEFT JOIN PRTHD.N_HOST_RQST_TYP NRT ON R.RQST_TYP_CD = NRT.RQST_TYP_CD
GROUP BY R.MTER_RQST_ID,
NRT.TYP_DESC
),
PO_DETAILS (
select A.*
FROM (
SELECT distinct PRTHD.BYO_PO.DSVC_TYP_CD,
RT.RQST_ID,
RT.HOST_TYPE,
PRTHD.BYO_PO.PO_CMT_TXT,
PRTHD.BYO_PO.BYO_NBR,
CE
WHEN PRTHD.BYO_PO.DSVC_TYP_CD = 2 THEN RIGHT('00' || PRTHD.BYO_PO.BYO_NBR, 2)
ELSE RIGHT('00' || PRTHD.BYO_PO_LOC_SKU.LOC_NBR, 2)
END || PRTHD.BYO_PO.acct_po_typ_cd || RIGHT('00000' || PRTHD.BYO_PO.PO_CTRL_NBR, 5) PO,
PRTHD.BYO_PO.ORD_REF_NBR,
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR,
PRTHD.BYO_PO_LOC_SKU.LOC_NBR,
PRTHD.BYO_PO_LOC_SKU.SKU_NBR,
CT(PRTHD.BYO_PO_LOC_SKU.ORD_QTY INTEGER) ORD_QTY,
PRTHD.BYO_PO.CRT_DT,
PRTHD.BYO_PO.PO_CTRL_NBR,
M.MVNDR_NM,
PRTHD.BYO_PO.MVNDR_NBR,
PRTHD.BYO_PO.OCYC_SOQ_RSN_CD RSN_CD
FROM (
(
PRTHD.BYO_PO BP
INNER JOIN PRTHD.BYO_PO_LOC_SKU ON (
PRTHD.BYO_PO.ORD_SEQ_NBR = PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR
)
AND (
PRTHD.BYO_PO.PO_CTRL_NBR = PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR
)
AND (
PRTHD.BYO_PO.ACCT_PO_TYP_CD = PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD
)
AND (
PRTHD.BYO_PO.MKT_DC_NBR = PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR
)
AND (
PRTHD.BYO_PO.MKT_DC_IND = PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND
)
AND (
PRTHD.BYO_PO.BYO_NBR = PRTHD.BYO_PO_LOC_SKU.BYO_NBR
)
)
INNER JOIN PRTHD.SKU ON PRTHD.BYO_PO_LOC_SKU.SKU_NBR = PRTHD.SKU.SKU_NBR
)
INNER JOIN PRTHD.BYO_PO_SKU ON (PRTHD.SKU.SKU_NBR = PRTHD.BYO_PO_SKU.SKU_NBR)
AND (
PRTHD.BYO_PO_LOC_SKU.BYO_NBR = PRTHD.BYO_PO_SKU.BYO_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.MKT_DC_IND = PRTHD.BYO_PO_SKU.MKT_DC_IND
)
AND (
PRTHD.BYO_PO_LOC_SKU.MKT_DC_NBR = PRTHD.BYO_PO_SKU.MKT_DC_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.ACCT_PO_TYP_CD = PRTHD.BYO_PO_SKU.ACCT_PO_TYP_CD
)
AND (
PRTHD.BYO_PO_LOC_SKU.PO_CTRL_NBR = PRTHD.BYO_PO_SKU.PO_CTRL_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.ORD_SEQ_NBR = PRTHD.BYO_PO_SKU.ORD_SEQ_NBR
)
AND (
PRTHD.BYO_PO_LOC_SKU.PO_LINE_NBR = PRTHD.BYO_PO_SKU.PO_LINE_NBR
)
LEFT JOIN PRTHD.MVNDR M ON M.MVNDR_NBR = PRTHD.BYO_PO.MVNDR_NBR
INNER JOIN RQST_TYPE RT ON TRIM(SUBSTR(BP.PO_CMT_TXT, 6, 11)) = RT.RQST_ID
) A
)
Select P.RQST_ID,
P.DSVC_TYP_CD,
CE
WHEN P.DSVC_TYP_CD = 1 THEN 'DTS'
WHEN P.DSVC_TYP_CD = 2 THEN 'RDC AGG'
WHEN P.DSVC_TYP_CD = 3 THEN 'RDCX'
END DSVC_TYP_DESC,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN 'Y'
ELSE 'N'
END RDC_AGG_PEG_FLG,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN P.ORD_REF_NBR
ELSE P.PO
END PO_NBR,
P.BYO_NBR,
P.PO_CTRL_NBR,
P.CRT_DT,
P.HOST_TYPE,
P.MVNDR_NBR,
P.MVNDR_NM,
CE
WHEN P.DSVC_TYP_CD = 2
AND S.STR_NBR IS NOT NULL THEN AR.MKT_DC_NBR
ELSE P.MKT_DC_NBR
END MKT_DC_NBR,
P.LOC_NBR,
COALESCE(SKU.MER_DEPT_NBR || '-' || D.SHRT_DEPT_NM, '') DEPT,
COALESCE(
SKU.MER_CLS_NBR || '-' || MC.SHRT_CLS_DESC,
''
) CLS,
COALESCE(
SKU.MER_SUB_CLS_NBR || '-' || MSC.SHRT_SUBCLS_DESC,
''
) SUB_CLS,
P.SKU_NBR,
P.ORD_QTY,
COALESCE(
SD.AVG_DC_LCOST_AMT * COALESCE(P.ORD_QTY, 0),
MSM.CURR_COST_AMT * COALESCE(P.ORD_QTY, 0)
) TOTAL_COST,
SD.AVG_DC_LCOST_AMT SD_COST,
MSM.CURR_COST_AMT STR_CURR_COST,
MSD.CURR_COST_AMT DC_CURR_COST,
P.PO_CMT_TXT,
P.RSN_CD
FROM PO_DETAILS P --SKU HIERARCHY INFO
LEFT JOIN PRTHD.SKU SKU ON SKU.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.DEPT D ON SKU.MER_DEPT_NBR = D.DEPT_NBR
LEFT JOIN PRTHD.MER_CLS MC ON MC.MER_DEPT_NBR = SKU.MER_DEPT_NBR
AND MC.MER_CLS_NBR = SKU.MER_CLS_NBR
LEFT JOIN PRTHD.MER_SUB_CLS MSC ON MSC.MER_DEPT_NBR = SKU.MER_DEPT_NBR
AND MSC.MER_CLS_NBR = SKU.MER_CLS_NBR
AND MSC.MER_SUB_CLS_NBR = SKU.MER_SUB_CLS_NBR
LEFT JOIN PRTHD.MVNDR_SKU_DC MSD ON MSD.MVNDR_NBR = P.MVNDR_NBR
AND MSD.SKU_NBR = P.SKU_NBR
AND MSD.DC_NBR = P.LOC_NBR
LEFT JOIN PRTHD.STR S ON S.STR_NBR = P.LOC_NBR
LEFT JOIN PRTHD.SKU_DC SD ON SD.DC_NBR = P.MKT_DC_NBR
AND SD.SKU_NBR = P.SKU_NBR
LEFT JOIN PRTHD.MVNDR_SKU_MKT MSM ON MSM.MVNDR_NBR = P.MVNDR_NBR
AND MSM.SKU_NBR = P.SKU_NBR
AND MSM.MKT_NBR = S.MKT_NBR
LEFT JOIN PRTHD.AGG_RQST AR ON AR.PO_NBR = P.ORD_REF_NBR
AND P.MVNDR_NBR = AR.MVNDR_NBR
AND SKU.MER_DEPT_NBR = AR.MER_DEPT_NBR
AND AR.ORD_DT >= P.CRT_DT

incorrect syntax in over and partition by with temporary tables

I have a partition-by function in my stored procedure which calls for a temporary table from a previous partition-by function. The table that I created with the previous partition by function is #tempVehicleManifestRow which in turn is what I call for the next partition by function. What happens is that it shoes the error
"incorrect syntax near ' #tempVehicleManifestRow'"
Why is this happening? Isn't it that I have already generated a temporary table with the data needed even before I actually selected it?
I have attached below the partition by functions I used.
This is my first partition by function:
;WITH A AS
(
SELECT ROW_NUMBER() OVER(ORDER BY
CASE
when #pOrderby = 'SortByGender' then T.Gender
when #pOrderby = 'SortByCost' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByPickupDate' then cast(T.colPickUpDate as varchar(20))
when #pOrderby = 'SortByLastName' then T.LastName
when #pOrderby = 'SortByFirstName' then T.FirstName
when #pOrderby = 'SortByEmployeeID' then cast(T.colSeafarerIdInt as varchar(20))
when #pOrderby = 'SortByShip' then T.VesselName
when #pOrderby = 'SortByTitle' then T.RankName
when #pOrderby = 'SortByRouteFrom' then T.RouteFrom
when #pOrderby = 'SortByRouteTo' then T.RouteTo
when #pOrderby = 'SortByFromCity' then T.colFromVarchar
when #pOrderby = 'SortByToCity' then T.colToVarchar
when #pOrderby = 'SortByVehicleTypeName' then T.VehicleTypeName
when #pOrderby = 'SortByStatus' then T.VehicleTypeName
when #pOrderby = 'SortByCostCenter' then T.colCostCenterCodeVarchar
when #pOrderby = 'SortByNationality' then T.Nationality
when #pOrderby = 'SortByVehicleVendor' then T.VehicleVendorname
when #pOrderby = 'SortByRecordLocator' then T.colRecordLocatorVarchar
when #pOrderby = 'SortByOnOffdate' then cast(T.colOnOffDate as varchar(20))
when #pOrderby = 'SortByPickupTime' then cast(T.colPickUpTime as varchar(20))
when #pOrderby = 'SortByOnOff' then T.colSFStatus
when #pOrderby = 'SortByHotel' then T.HotelVendorName
ELSE
T. VehicleVendorname
END ,
CASE WHEN #pOrderby = 'SortByPickupDate' then cast(T.colPickUpTime as varchar(20))
ELSE T.FirstName
END
) AS xRow,
* FROM #tempVehicleManifest T
) SELECT * INTO #tempVehicleManifestRow FROM A ORDER BY A.xRow
This is the partition-by that is are having problems:
;WITH CC AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY CC.colRecordLocatorVarchar, CC.colSeafarerIdInt,
CC.colOnOffVarchar , CC.colVehicleVendorIDInt
ORDER BY CC.colTagIDInt DESC) xRow, CC.*
FROM (
SELECT distinct
A.xRow,
A.colTransVehicleIDBigint,
A.colSeafarerIdInt, A.LastName, A.FirstName,
A.colIdBigint, A.colTravelReqIDInt,
A.colRecordLocatorVarchar, A.colOnOffDate,
A.colRequestIDInt, A.colVehicleVendorIDInt,
A.VehicleVendorname, A.colVehiclePlateNoVarchar,
A.colPickUpDate, A.colPickUpTime,
A.colDropOffDate, A.colDropOffTime,
A.colConfirmationNoVarchar, A.colVehicleStatusVarchar,
A.colVehicleTypeIdInt, A.VehicleTypeName, A.colSFStatus,
A.colRouteIDFromInt, A.RouteFrom, A.colRouteIDToInt, A.RouteTo,
A.colFromVarchar, A.colToVarchar, A.colRemarksForAuditVarchar,
A.colHotelIDInt, A.HotelVendorName, A.colRankIDInt, A.RankName,
A.colCostCenterIDInt, A.colCostCenterCodeVarchar,
Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar)),
A.colIsVisibleBit,
A.colContractIdInt, A.Gender, A.colVesselIdInt,
A.VesselName, UserID = #pUserID, A.colSeqNoInt
, A.colDriverIDInt
--, A.colIsNoVehicleNeeded
, A.colVehicleDispatchTime
, FlightNo =A.colFlightNoVarchar
, Carrier = A.colMarketingAirlineCodeVarchar
, Departure = A.colDepartureAirportLocationCodeVarchar
, Arrival = A.colArrivalAirportLocationCodeVarchar
, DeptDate = A.colDepartureDateTime
, ArrDate = A.colArrivalDateTime
, PA.PassportNo
, PA.PassportExp
, PA.PassportIssued
, BR.Birthday
, ISNULL(CC.colIsActiveBit,0) as colIsActiveBitTagged
, CC.colCreatedByVarchar as createdUserTag
, CC.colModifiedByVarchar as modifiedUserTag
, CC.colVehicleVendorIDInt as taggedVehicleVendorId
#tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON
A.colSeafarerIdInt = B.colSeafarerIdInt AND
A.colVehicleVendorIDInt = B.colVehicleVendorIDInt AND
A.colPickUpDate = B.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(B.colRecordLocatorVarchar,'')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON
A.colSeafarerIdInt = Hide.colSeafarerIdInt AND
A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt AND
A.colPickUpDate = Hide.colPickUpDate AND
ISNULL(A.colRecordLocatorVarchar,'') = ISNULL(Hide.colRecordLocatorVarchar,'') AND
ISNULL(Hide.colIsVisibleBit,1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint AND
B.colTravelReqIDInt = CC.colTravelReqIDInt AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE
( B.colConfirmedManifestIDBigint IS NULL
OR
Hide.colTransVehicleIDBigint IS NOT NULL
)
ORDER BY A.xRow
)
) SELECT * INTO #tempManifestNew
You have missed the FROM CLAUSE in this query near #tempVehicleManifestRow A. Here is the correct query.
;WITH CC
AS (
SELECT ROW_NUMBER() OVER (
PARTITION BY CC.colRecordLocatorVarchar
,CC.colSeafarerIdInt
,CC.colOnOffVarchar
,CC.colVehicleVendorIDInt ORDER BY CC.colTagIDInt DESC
) xRow
,CC.*
FROM (
SELECT DISTINCT A.xRow
,A.colTransVehicleIDBigint
,A.colSeafarerIdInt
,A.LastName
,A.FirstName
,A.colIdBigint
,A.colTravelReqIDInt
,A.colRecordLocatorVarchar
,A.colOnOffDate
,A.colRequestIDInt
,A.colVehicleVendorIDInt
,A.VehicleVendorname
,A.colVehiclePlateNoVarchar
,A.colPickUpDate
,A.colPickUpTime
,A.colDropOffDate
,A.colDropOffTime
,A.colConfirmationNoVarchar
,A.colVehicleStatusVarchar
,A.colVehicleTypeIdInt
,A.VehicleTypeName
,A.colSFStatus
,A.colRouteIDFromInt
,A.RouteFrom
,A.colRouteIDToInt
,A.RouteTo
,A.colFromVarchar
,A.colToVarchar
,A.colRemarksForAuditVarchar
,A.colHotelIDInt
,A.HotelVendorName
,A.colRankIDInt
,A.RankName
,A.colCostCenterIDInt
,A.colCostCenterCodeVarchar
,Nationality = RTRIM(LTRIM(N.colNationalityCodeVarchar)) + '-' + RTRIM(LTRIM(N.colNationalityDescriptionVarchar))
,A.colIsVisibleBit
,A.colContractIdInt
,A.Gender
,A.colVesselIdInt
,A.VesselName
,UserID = #pUserID
,A.colSeqNoInt
,A.colDriverIDInt
--, A.colIsNoVehicleNeeded
,A.colVehicleDispatchTime
,FlightNo = A.colFlightNoVarchar
,Carrier = A.colMarketingAirlineCodeVarchar
,Departure = A.colDepartureAirportLocationCodeVarchar
,Arrival = A.colArrivalAirportLocationCodeVarchar
,DeptDate = A.colDepartureDateTime
,ArrDate = A.colArrivalDateTime
,PA.PassportNo
,PA.PassportExp
,PA.PassportIssued
,BR.Birthday
,ISNULL(CC.colIsActiveBit, 0) AS colIsActiveBitTagged
,CC.colCreatedByVarchar AS createdUserTag
,CC.colModifiedByVarchar AS modifiedUserTag
,CC.colVehicleVendorIDInt AS taggedVehicleVendorId
-- HERE YOU HAVE MISSED FROM CLAUSE
FROM #tempVehicleManifestRow A
LEFT JOIN TblVehicleManifestConfirmed B ON A.colSeafarerIdInt = B.colSeafarerIdInt
AND A.colVehicleVendorIDInt = B.colVehicleVendorIDInt
AND A.colPickUpDate = B.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(B.colRecordLocatorVarchar, '')
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--not visible to vendor but not realy cancelled
LEFT JOIN TblVehicleManifestConfirmed Hide ON A.colSeafarerIdInt = Hide.colSeafarerIdInt
AND A.colVehicleVendorIDInt = Hide.colVehicleVendorIDInt
AND A.colPickUpDate = Hide.colPickUpDate
AND ISNULL(A.colRecordLocatorVarchar, '') = ISNULL(Hide.colRecordLocatorVarchar, '')
AND ISNULL(Hide.colIsVisibleBit, 1) = 0
AND A.colRouteIDFromInt = B.colRouteIDFromInt
AND A.colRouteIDToInt = B.colRouteIDToInt
--added new table
LEFT JOIN TblTag_Vehicle CC ON B.colIdBigint = CC.colIdBigint
AND B.colTravelReqIDInt = CC.colTravelReqIDInt
AND B.colSeafarerIdInt = CC.colSeafarerIdInt
--end new added table
LEFT JOIN dbo.TblVehiclePlates VP ON VP.colPlateID = B.colVehiclePlateNoVarchar
LEFT JOIN dbo.TblSeafarer S ON S.colSeafarerIdInt = A.colSeafarerIdInt
LEFT JOIN TblNationality N ON N.colNatioalityIdInt = S.colNationalityIDInt
LEFT JOIN #TempPassport PA ON A.colSeafarerIdInt = PA.SeafarerId
LEFT JOIN tmRemarks_Birthday BR ON BR.FK_ItineraryRefID = A.colRecordLocatorVarchar
JOIN #tempVehicleVendor VE ON VE.colVehicleVendorIDInt = A.colVehicleVendorIDInt
WHERE (
B.colConfirmedManifestIDBigint IS NULL
OR Hide.colTransVehicleIDBigint IS NOT NULL
)
) AS x -- missing alias declaration, required in TSQL
)
SELECT *
INTO #tempManifestNew