Adding a SUM Column to a Query - sql

I'm trying to do a query that returns the information of a purchase bill, but also there's another table that has detail of the bill, but I need to add that total to the other query, but I can't add the column, because it says that I need to have in the group by the same objects that in the select, and I tried it this way, but it says that it returns more than one value. Help please! :D
SELECT fc.fecha_factura_compra AS fecha, fc.id_factura AS no_factura, fc.serie,
o.abreviatura + CAST(p.corr_id AS VARCHAR(255)) AS codigo_trupp,
p.nombre, fc.dias_credito, fc.tipo_cambio,
(SELECT SUM(dc.peso_neto * dc.precio_unitario)
FROM detalle_compra AS dc
GROUP BY dc.id_proveedor,
dc.id_factura,
dc.serie) AS total
FROM factura_compra AS fc,
origen AS o,
proveedor AS p,
detalle_compra AS dc
WHERE fc.id_proveedor = p.id_proveedor
AND dc.id_proveedor = p.id_proveedor
AND dc.id_factura = fc.id_factura
AND p.id_origen = o.id_origen
AND dc.serie = fc.serie
AND dc.id_factura = fc.id_factura
AND dc.id_proveedor = fc.id_proveedor
AND fc.activo_inactivo = 'true'
AND fc.anulada = 'false'

The construction with the subquery is extremely slow and to be avoided. A better solution is to write the query like below.
To add a total to a query you need to group by over all the other fields in your result set.
SELECT fc.fecha_factura_compra AS fecha
, fc.id_factura AS no_factura
, fc.serie
, o.abreviatura + CAST(p.corr_id AS VARCHAR(255)) AS codigo_trupp
, p.nombre
, fc.dias_credito
, fc.tipo_cambio
, SUM(dc.peso_neto * dc.precio_unitario) AS total
FROM factura_compra AS fc
JOIN proveedor AS p
ON fc.id_proveedor = p.id_proveedor
JOIN origen AS o
ON p.id_origen = o.id_origen
JOIN detalle_compra AS dc
ON dc.id_factura = fc.id_factura
AND dc.serie = fc.serie
AND dc.id_factura = fc.id_factura
AND dc.id_proveedor = fc.id_proveedor
AND dc.id_proveedor = p.id_proveedor
WHERE fc.activo_inactivo = 'true'
AND fc.anulada = 'false'
GROUP BY fc.fecha_factura_compra
, fc.id_factura
, fc.serie
, o.abreviatura + CAST(p.corr_id AS VARCHAR(255))
, p.nombre
, fc.dias_credito
, fc.tipo_cambio

Instead of grouping by the columns, you should restrict the sub-select on the join columns and omit detalle_compra from the outer select:
SELECT fc.fecha_factura_compra as fecha,
fc.id_factura as no_factura,
fc.serie,
o.abreviatura+CAST(p.corr_id as varchar(255)) as Codigo_Trupp,
p.nombre,
fc.dias_credito,
fc.tipo_cambio,
(select sum(peso_neto*precio_unitario)
from detalle_compra
where serie = fc.serie and
id_factura = fc.id_factura and
id_proveedor = fc.id_proveedor) as Total
FROM factura_compra as fc,origen as o, proveedor as p
WHERE fc.id_proveedor = p.id_proveedor and
p.id_origen = o.id_origen and
fc.activo_inactivo = 'true' and
fc.anulada = 'false'
Side note: Use the BIT type to store booleans:
...
fc.activo_inactivo = 1 and
fc.anulada = 0

Related

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.

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

SQL Server: SUM() with internal SELECT and sub SELECT. Error every time

QUESTION REWORDED
I had the following column definition in an SQL statement with its own GROUP BY...
SUM((SELECT a.CONT_TOT
FROM (SELECT gl2.VisitID, gl2.MessageID, gl2.BillOfLading, COUNT(gl2.ContainerID) AS CONT_TOT
FROM dbo.tblEDIGoodsLines AS gl2
WHERE gl2.VisitID = gl.VisitID AND gl2.MessageID = gl.MessageID AND gl2.BillOfLading = gl.BillOfLading
GROUP BY gl2.VisitID, gl2.MessageID, gl2.BillOfLading) AS a)) as TotalContainers,
...etc
And I continuously got this error.
Cannot perform an aggregate function on an expression containing an
aggregate or a subquery.
I am trying to get the TOTAL number of lines in the outside/bigger SELECT, and a total number of UNIQUE container counts in the TOTUCONT.
What am I doing wrong?
Here is the greater SQL query, to illustrate my point about GROUP BY and sub-queries in an aggregate function like SUM():
SELECT
gl.MessageID,
gl.BillOfLading,
gl.[Description],
CASE WHEN e.PortID = 9 THEN 'Export'
WHEN e.PortID = 11 THEN 'Import'
ELSE 'ERROR'
END AS Direction,
CASE WHEN ctypes.ID IS NOT NULL
THEN ctypes.ContainerSizeType
ELSE 'OTH'
END AS CSizeType,
ctypes.Length_ft + 'ft ' + ctypes.Height_ft + 'ft - ' + ctypes.Characteristics + ' (' + COALESCE(ctypes.Codes1995, ctypes.Codes1984) + ')' AS ContainerType,
COUNT(gl.ContainerID) AS TOTCONT,
SUM(a.CTOTAL) AS TOTUCONT
FROM tblEDIGoodsLines AS gl
INNER JOIN tblEDIEquipmentLines AS el
ON el.MessageID = gl.MessageID AND
el.ContainerID = gl.ContainerID
INNER JOIN tblEDI AS e
ON CHARINDEX(e.MessageID, gl.MessageID) > 0 AND
e.VisitID = gl.VisitID AND
CHARINDEX('EXCEL', e.MessageRelease) = 0 AND
e.Status = 1
LEFT JOIN tblContainerTypesISO6346 AS ctypes
ON ctypes.Codes1984 = el.SizeAndType OR
ctypes.Codes1995 = el.SizeAndType
LEFT JOIN (SELECT gl2.MessageID, gl2.VisitID, gl2.BillOfLading, gl2.description, COUNT(DISTINCT gl2.ContainerID) AS CTOTAL
FROM tblEDIGoodsLines AS gl2
WHERE gl2.MessageID = gl.MessageID
AND gl2.VisitID = gl.VisitID
and gl2.BillOfLading = gl.billoflading
and gl2.description = gl.description
GROUP BY gl2.MessageID, gl2.VisitID, gl2.BillOfLading, gl2.description) AS a
ON a.MessageID = gl.MessageID AND a.VisitID = gl.VisitID AND a.BillOfLading = gl.billoflading AND a.description = gl.description
WHERE gl.Status = 1
AND gl.VisitID = 22987
GROUP BY
gl.MessageID,
gl.BillOfLading,
gl.[Description],
CASE WHEN e.PortID = 9 THEN 'Export'
WHEN e.PortID = 11 THEN 'Import'
ELSE 'ERROR'
END,
CASE WHEN ctypes.ID IS NOT NULL
THEN ctypes.ContainerSizeType
ELSE 'OTH'
END,
ctypes.Length_ft + 'ft ' + ctypes.Height_ft + 'ft - ' + ctypes.Characteristics + ' (' + COALESCE(ctypes.Codes1995, ctypes.Codes1984) + ')'
The above does not work anyway, as I am trying to solve this by separating the "column" SELECT into it's own JOIN query, but now I get this:
The multi-part identifier "gl.MessageID" could not be bound.
So this implies, that the LEFT JOIN (SELECT...) is invalid?
Thanks again
UPDATE 2
Here is a data sample to explain further:
So you can see the outcome I want, TOTCONT to add up to '4'. That's easy - just count the number of rows, but TOTUCONT to count only the Container ID once.
Try refactoring the code to be more like this (as I commented earlier). It may also help with the other issues you are dealing with:
with cte_ctotal
as (
select gl2.MessageID,
gl2.VisitID,
gl2.BillOfLading,
gl2.description,
COUNT(distinct gl2.ContainerID) as CTOTAL
from tblEDIGoodsLines as gl2
group by gl2.MessageID,
gl2.VisitID,
gl2.BillOfLading,
gl2.description
),
cte_containers
as (
select
a.ContainerID,
gl.MessageID,
gl.VisitID,
gl.BillOfLading,
gl.Description,
case
when e.PortID = 9
then 'Export'
when e.PortID = 11
then 'Import'
else 'ERROR'
end as Direction,
case
when ctypes.ID is not null
then ctypes.ContainerSizeType
else 'OTH'
end as CSizeType,
ctypes.Length_ft + 'ft ' + ctypes.Height_ft + 'ft - ' + ctypes.Characteristics + ' (' + COALESCE(ctypes.Codes1995, ctypes.Codes1984) + ')' as ContainerType,
from tblEDIGoodsLines gl
inner join tblEDIEquipmentLines el on el.MessageID = gl.MessageID
and el.ContainerID = gl.ContainerID
inner join tblEDI e on CHARINDEX(e.MessageID, gl.MessageID) > 0
and e.VisitID = gl.VisitID
and CHARINDEX('EXCEL', e.MessageRelease) = 0
and e.status = 1
left join tblContainerTypesISO6346 ctypes on ctypes.Codes1984 = el.SizeAndType
or ctypes.Codes1995 = el.SizeAndType
where gl.status = 1
and gl.VisitID = 22987
)
select
c.MessageID,
c.BillOfLading,
c.Description,
c.Direction,
c.CSizeType,
c.ContainerType,
COUNT(c.ContainerID) as TOTCONT,
SUM(COALESCE(ct.CTOTAL,0)) as TOTUCONT
from cte_containers c
left join cte_ctotal ct on ct.MessageID = c.MessageID
and ct.VisitID = c.VisitID
and ct.BillOfLading = c.billoflading
and ct.description = c.description
group by c.MessageID,
c.BillOfLading,
c.Description,
c.Direction,
c.CSizeType,
c.ContainerType;
Try this,
(SELECT SUM(a.CONT_TOT)
FROM (SELECT gl2.VisitID, gl2.MessageID, gl2.BillOfLading, COUNT(gl2.ContainerID) AS CONT_TOT
FROM dbo.tblEDIGoodsLines AS gl2
WHERE gl2.VisitID = gl.VisitID AND gl2.MessageID = gl.MessageID AND gl2.BillOfLading = gl.BillOfLading
GROUP BY gl2.VisitID, gl2.MessageID, gl2.BillOfLading) AS a) as TotalContainers,
I think you can simplify this to:
(SELECT COUNT(gl2.ContainerID)
FROM dbo.tblEDIGoodsLines gl2
WHERE gl2.VisitID = gl.VisitID AND
gl2.MessageID = gl.MessageID AND
gl2.BillOfLading = gl.BillOfLading
) as TotalContainers,
Notes:
The outer SUM() is unnecessary. You can do the aggregation in the subqueries.
You do not need two levels of subqueries.
The GROUP BY is unnecessary. An aggregation query with no GROUP BY always returns exactly one row, which is what you want for a scalar subquery.
Depending on the rest of your query, this still might not work in your full query. If this is the case, then you should ask a new question, with sample data, desired results, and (a simplified version of) the query that does not work.
Change to this:
SUM(a.CONT_TOT) as TotalContainers
FROM (
SELECT COUNT(gl2.ContainerID) AS CONT_TOT
FROM dbo.tblEDIGoodsLines AS gl2
WHERE gl2.VisitID = gl.VisitID AND gl2.MessageID = gl.MessageID AND gl2.BillOfLading = gl.BillOfLading
GROUP BY gl2.VisitID, gl2.MessageID, gl2.BillOfLading
) AS a,
You may need to use parentheses at the end depending on the use of the code.
I removed additional columns from the SELECT list as they are not needed to get the SUM() (unless you need them for something else?).
Edit
Remove the WHERE clause from the last JOIN:
WHERE gl2.MessageID = gl.MessageID
AND gl2.VisitID = gl.VisitID
and gl2.BillOfLading = gl.billoflading
and gl2.description = gl.description
These conditions are applied in the ON clause.

SQL Query - How to suppress repeating values in the result set?

I'm trying to suppress the repeating values in TotalCarton column. Have tried to replace the value either blank or null but went failed. Any help?
Here is the SQL Script:
SELECT ORDERS.StorerKey,
ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = ( CASE BAX_PACK_DTL.PackType WHEN 'C' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
TotalPallet = ( CASE BAX_PACK_DTL.PackType WHEN 'P' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'C' AND PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'P' AND PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM ORDERS WITH (NOLOCK) INNER JOIN ORDERDETAIL WITH (NOLOCK) ON ORDERS.StorerKey = ORDERDETAIL.StorerKey
AND ORDERS.OrderKey = ORDERDETAIL.OrderKey
INNER JOIN PICKDETAIL WITH (NOLOCK) ON ORDERDETAIL.StorerKey = PICKDETAIL.StorerKey
AND ORDERDETAIL.OrderKey = PICKDETAIL.OrderKey
AND ORDERDETAIL.OrderLineNumber = PICKDETAIL.OrderLineNumber
INNER JOIN BAX_PACK_DTL WITH (NOLOCK) ON PICKDETAIL.OrderKey = BAX_PACK_DTL.OrderKey
AND PICKDETAIL.PickDetailKey = BAX_PACK_DTL.PickDetailKey
WHERE (SELECT COUNT(DISTINCT(ORDERKEY)) FROM PICKDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey ) > 0
AND BAX_PACK_DTL.PackKey = '0000000211'
AND BAX_PACK_DTL.OuterPackID IN
('P111111111',
'P22222222',
'P33333333')
GROUP BY ORDERS.StorerKey,
ORDERS.OrderKey,
ORDERS.ExternOrderKey,
ORDERS.HAWB,
ORDERS.SO,
ORDERS.EditWho,
ORDERS.AddDate,
PICKDETAIL.WaveKey,
BAX_PACK_DTL.OuterPackID,
BAX_PACK_DTL.PackKey,
BAX_PACK_DTL.PackType
ORDER BY BAX_PACK_DTL.OuterPackID ASC
Below is the current result set based on the query above.
Your code looks really strange. I would expect the query to use conditional aggregation and look more like this:
SELECT ORDERS.StorerKey, ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'C' THEN BAX_PACK_DTL.OuterPackID END),
TotalPallet = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'P' THEN BAX_PACK_DTL.OuterPackID END),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'C' AND pbd.PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'P' AND pbd.PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM . . .
GROUP BY ORDERS.StorerKey, ORDERS.OrderKey, Upper(ORDERS.ExternOrderKey),
Upper(ORDERS.EditWho), ORDERS.AddDate;
This may not be exact. You have not qualified column names, given the table structure, and are using very arcane query syntax, mixing subqueries and aggregations. But it should give an idea.

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