Error in JPQL Query: "unexpected token: ( near line 1" - sql

i have this working sql query:
select temp.pratica_regola_id FROM ( SELECT TABLE1.pratica_regola_id, TABLE1.CON FROM ( SELECT pratica_regola_id, COUNT(*) AS CON FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1 LEFT JOIN (select LRP.entita_legame_id AS EL1 from legame_regola_pratica LRP JOIN entita_legame EL ON LRP.entita_legame_id = EL.entita_legame_id where LRP.pratica_regola_id = 418 AND LRP.REGOLA_ID = 1426 AND el.tp_entita_legame_id =1 ) TAB_ENT_LEG ON TAB_ENT_LEG.EL1 = L1.entita_legame_id WHERE TAB_ENT_LEG.EL1 IS NOT NULL AND l1.tp_livello_legame_id = 2 and l1.pratica_regola_id in (select pratica_regola_id from pratica_regola where tp_stato_pratica_id = 2)) GROUP BY PRATICA_REGOLA_ID ) TABLE1 INNER JOIN ( SELECT pratica_regola_id, COUNT(*) AS TOT FROM (SELECT DISTINCT PRATICA_REGOLA_ID, ENTITA_LEGAME_ID FROM legame_regola_pratica L1) group by pratica_regola_id) TABLE2 on TABLE1.pratica_regola_id = TABLE2.pratica_regola_id where TABLE1.CON = TABLE2.TOT) temp WHERE CON = (SELECT COUNT(*) FROM legame_regola_pratica where pratica_regola_id = 418 AND REGOLA_ID = 1426 and dat_ora_can is null) and pratica_regola_id <> 418;
I tried to tranlsate it in JPQL in this kind:
#Query("SELECT TABLE_TEMP_1.praticaRegolaId FROM ("
+ "SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM ("
+ "SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1 LEFT JOIN ("
+ "SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameId"
+ "WHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)"
+ "TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM"
+ " praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))"
+ "GROUP BY praticaRegolaId) AS TABLE_TEMP_2"
+ "INNER JOIN ("
+ "SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId"
+ ") TABLE_TEMP_3" + "ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaId" + "WHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )"
+ "AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM LegameRegolaPratica WHERE praticaRegola = :praticaRegola"
+ "AND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ")
but i get this error message:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 42 [SELECT TABLE_TEMP_1.praticaRegolaId FROM (SELECT TABLE_TEMP_2.praticaRegolaId, TABLE_TEMP_2.numero_entita FROM (SELECT praticaRegolaId, COUNT(*) AS numero_entita FROM (SELECT DISTINCT PraticaRegola.praticaRegolaId, EntitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1 LEFT JOIN (SELECT LRP.entitaLegame.entitaLegameId AS EL_1 FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP JOIN EntitaLegame EL ON LRP.entitaLegame.entitaLegameId = EL.entitaLegameIdWHERE LRP.praticaRegola = :praticaRegola AND LRP.regola = :praticaRegola.regola AND EL.tpEntitaLegame = :tipoEntitaLegame)TAB_ENT_LEG ON TAB_ENT_LEG.EL_1 = LRP_1.entitaLegame.entitaLegameId WHERE TAB_ENT_LEG.EL_1 IS NOT NULL AND LRP_1.tpLivelloLegame = :tipoLivelloLegame AND LRP_1.praticaRegola.praticaRegolaId IN (SELECT praticaRegolaId FROM praticaRegola WHERE tpStatoPratica = :tipoStatoPratica))GROUP BY praticaRegolaId) AS TABLE_TEMP_2INNER JOIN (SELECT praticaRegolaId, COUNT(*) AS TOT FROM (SELECT DISTINCT LRP_1.praticaRegola.praticaRegolaId, LRP_1.entitaLegame.entitaLegameId FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica LRP_1) GROUP BY praticaRegolaId) TABLE_TEMP_3ON TABLE_TEMP_2.praticaRegolaId = TABLE_TEMP_3.praticaRegolaIdWHERE TABLE_TEMP_2.NUMERO_ENTITA = TABLE_TEMP_3.TOT )AS TABLE_TEMP_1 WHERE NUMERO_ENTITA = (SELECT COUNT(*) FROM it.aivebst.adaprice.rules.entities.LegameRegolaPratica WHERE praticaRegola = :praticaRegolaAND regola = :praticaRegola.regola AND dataOraCancellazione IS NULL) ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
Thank you

You may not have subqueries in the from clause of a HQL query. Use a native SQL query.
Quote from the documentation:
Note that HQL subqueries can occur only in the select or where clauses.

Related

SQL query with multiple CTE but getting "ERROR: relation "t" does not exist"

I'm trying to run a SQL query with multiple CTE but getting "ERROR: relation "t" does not exist"
Here is the code. What am I doing wrong?
WITH tmp AS (
Select a.tx_id, a.txo_index, a.address,b.tx_in_id from txo as a
inner join txin as b ON (a.tx_id = b.tx_out_id and a.txo_index= b.tx_out_index)
where a.tx_in_id = 0
),
tmp2 AS
(
Select tmp.tx_id,tmp.txo_index,tmp.address,tmp.tx_in_id,b.value as value_next,c.epoch_no as consumed_epoch,c.date as consumed_date from tmp
inner join txo as b ON
tmp.tx_in_id = b.tx_id and
tmp.address = b.address
inner join tx as c ON
tmp.tx_in_id = c.id
)
Update t
SET
t.tx_in_id = tmp2.tx_in_id,
t.value_next = tmp2.value_next,
t.consumed_epoch = tmp2.epoch_no,
t.consumed_date = tmp2.date
FROM txo as t
inner join tmp2 ON
t.tx_id = tmp2.tx_id and t.txo_index = tmp2.txo_index and t.address = tmp2.address
where t.tx_in_id =0
I believe referring to the table as an alias in the UPDATE and SET clause isn't allowed in postgres. Instead:
WITH tmp AS (
Select a.tx_id, a.txo_index, a.address,b.tx_in_id from txo as a
inner join txin as b ON (a.tx_id = b.tx_out_id and a.txo_index= b.tx_out_index)
where a.tx_in_id = 0
),
tmp2 AS
(
Select tmp.tx_id,tmp.txo_index,tmp.address,tmp.tx_in_id,b.value as value_next,c.epoch_no as consumed_epoch,c.date as consumed_date from tmp
inner join txo as b ON
tmp.tx_in_id = b.tx_id and
tmp.address = b.address
inner join tx as c ON
tmp.tx_in_id = c.id
)
Update txo
SET
tx_in_id = tmp2.tx_in_id,
value_next = tmp2.value_next,
consumed_epoch = tmp2.epoch_no,
consumed_date = tmp2.date
FROM tmp2
WHERE txo.tx_id = tmp2.tx_id
and txo.txo_index = tmp2.txo_index
and txo.address = tmp2.address
and txo.tx_in_id =0

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 Left Join issue

When I execute this:
SELECT i.descricao,
sii.quantidade quantidade_inicial,
sii.quantidade * i.valor valor_inicial
FROM itensvalor i
LEFT JOIN saldoinicialprodutositens sii
ON i.id = sii.iditemvalor
AND Isnull(sii.datahoraexclusao, '') = ''
WHERE sii.idSaldoInicialProduto IN (SELECT id FROM saldoInicialProdutos WHERE idmovimentodiario = 76)
It returns this:
And when I execute this:
SELECT i.descricao,
sfi.quantidade quantidade_final,
sfi.quantidade * i.valor valor_final
FROM itensvalor i
LEFT JOIN saldofinalprodutositens sfi
ON i.id = sfi.iditemvalor
AND Isnull(sfi.datahoraexclusao, '') = ''
WHERE sfi.idSaldoFinalProduto IN (SELECT id FROM saldoFinalProdutos WHERE idmovimentodiario = 76)
It returns this: (with the R$100,00)
But, finally, when I try to join the 2 tables, the value that refers to R$100,00 not appears.
I'm trying to join using this query:
SELECT i.descricao,
sii.quantidade quantidade_inicial,
sii.quantidade * i.valor valor_inicial,
sfi.quantidade quantidade_final,
sfi.quantidade * i.valor valor_final
FROM itensvalor i
LEFT JOIN saldofinalprodutositens sfi
ON i.id = sfi.iditemvalor
AND Isnull(sfi.datahoraexclusao, '') = ''
LEFT JOIN saldoinicialprodutositens sii
ON i.id = sii.iditemvalor
AND Isnull(sii.datahoraexclusao, '') = ''
WHERE sii.idSaldoInicialProduto IN (SELECT id FROM saldoInicialProdutos WHERE idmovimentodiario = 76)
AND sfi.idSaldoFinalProduto IN (SELECT id FROM saldoFinalProdutos WHERE idmovimentodiario = 76)
You need to move your WHERE inside the ON clause for that to work:
SELECT i.descricao,
sii.quantidade quantidade_inicial,
sii.quantidade * i.valor valor_inicial,
sfi.quantidade quantidade_final,
sfi.quantidade * i.valor valor_final
FROM itensvalor i
LEFT JOIN saldofinalprodutositens sfi
ON i.id = sfi.iditemvalor
AND Isnull(sfi.datahoraexclusao, '') = ''
and sfi.idSaldoFinalProduto IN (SELECT id FROM saldoFinalProdutos WHERE idmovimentodiario = 76)
LEFT JOIN saldoinicialprodutositens sii
ON i.id = sii.iditemvalor
AND Isnull(sii.datahoraexclusao, '') = ''
and sii.idSaldoInicialProduto IN (SELECT id FROM saldoInicialProdutos WHERE idmovimentodiario = 76)
Otherwise, your sfi.idSaldoFinalProduto is null, and the row is omited.

Selecting rows with MAX(Column value), DISTINCT by another column in SQL

I have two tables that I'm having difficulty with. OrderHed & UD11. OrderHed has 1 value for OrderNum=70960, but UD11 has 4 records for 70960.
I'm trying to return the max value of UD11.Key5 as a distinct record - what am I doing wrong?
Thanks!
SELECT TOP (100) PERCENT OrderHed.OrderNum,
OrderHed.OpenOrder,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
SUM(OrderDtl.ExtPriceDtl) AS Expr1,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
MAX(Ice.UD11.Key5) AS Expr2,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment
FROM Erp.Customer
RIGHT JOIN Ice.UD11
RIGHT JOIN Erp.OrderHed AS OrderHed ON Ice.UD11.Company = OrderHed.Company
AND Ice.UD11.Key1 = OrderHed.OrderNum
LEFT JOIN Erp.OrderRel AS OrderRel
RIGHT JOIN Erp.OrderDtl AS OrderDtl ON OrderRel.Company = OrderDtl.Company
AND OrderRel.OrderNum = OrderDtl.OrderNum
AND OrderRel.OrderLine = OrderDtl.OrderLine ON OrderHed.Company = OrderDtl.Company
AND OrderHed.OrderNum = OrderDtl.OrderNum ON Erp.Customer.Company = OrderHed.Company
AND Erp.Customer.CustNum = OrderHed.CustNum LEFT JOIN Erp.InvcDtl RIGHT JOIN Erp.ShipDtl ON Erp.InvcDtl.Company = Erp.ShipDtl.Company
AND Erp.InvcDtl.OrderNum = Erp.ShipDtl.OrderNum
AND Erp.InvcDtl.OrderLine = Erp.ShipDtl.OrderLine
AND Erp.InvcDtl.OrderRelNum = Erp.ShipDtl.OrderRelNum ON OrderRel.Company = Erp.ShipDtl.Company
AND OrderRel.OrderNum = Erp.ShipDtl.OrderNum
AND OrderRel.OrderLine = Erp.ShipDtl.OrderLine
AND OrderRel.OrderRelNum = Erp.ShipDtl.OrderRelNum GROUP BY OrderHed.OrderNum,
OrderHed.OrderDate,
OrderRel.Plant,
OrderHed.EntryPerson,
OrderHed.Company,
OrderHed.OpenOrder,
Erp.Customer.CustID,
Erp.Customer.NAME,
Erp.InvcDtl.InvoiceNum,
OrderHed.PONum,
Ice.UD11.Key1,
Ice.UD11.Key2,
Ice.UD11.Key3,
Ice.UD11.Key4,
Ice.UD11.Character01,
Ice.UD11.Number01,
Ice.UD11.Date01,
Ice.UD11.Date02,
Ice.UD11.Date03,
Ice.UD11.ShortChar01,
Ice.UD11.ShortChar02,
Ice.UD11.ShortChar03,
Ice.UD11.ShortChar04,
Ice.UD11.ShortChar05,
OrderHed.OrderComment HAVING (OrderHed.Company = N'011')
AND (Erp.InvcDtl.InvoiceNum IS NULL)
AND (OrderHed.OrderNum = 70960)
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY OrderNum ORDER BY key5 DESC) rn
FROM (... /* my huge query */) q
) q
WHERE rn = 1

SqlCommand: Incorrect syntax near the keyword 'OVER'

I'm trying to get data from database show it in a ASP.NET DataGrid.
It's showing the above mentioned error.
This is the select command:
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
strSql = "WITH TempTable AS(Select JobDetails.JobCode,JobDetails.CurrentStatus,MasterModel.Name As ModelNumber,MasterModel.Code As ModelCode,MasterBrand.Code As BrandCode,MasterBrand.Name As BrandName,MasterDeviceType.Code As DeviceCode,MasterDeviceType.Name As DType,ROW_NUMBER() OVER (ORDER BY " + OrderBy + ") AS RowNumber From JobDetails JobDetails Inner Join MasterDeviceType ON JobDetails.DType = MasterDeviceType.Code Inner Join MasterBrand ON JobDetails.BCode = MasterBrand.Code Inner join MasterModel ON JobDetails.ModelNumber = MasterModel.Code WHERE 1 = 1) SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
MasterJobList objList = new MasterJobList();
DataTable dt = new DataTable();
dt = objDB.GetDataTableFromSQL(strSql);
if (dt != null)
{
foreach (DataRow Dr in dt.Rows)
{
jobs obj = new jobs();
obj.JobCode =Convert.ToInt32(Dr["JobCode"].ToString());
if (Dr["DType"] != DBNull.Value)
obj.DType = Dr["DType"].ToString();
else
obj.DType = "";
if (Dr["BrandName"] != DBNull.Value)
obj.BrandName = Dr["BrandName"].ToString();
else
obj.BrandName = "";
if (Dr["ModelNumber"] != DBNull.Value)
obj.ModelNumber = Dr["ModelNumber"].ToString();
else
obj.ModelNumber = "";
if (Dr["CurrentStatus"] != DBNull.Value)
obj.CurrentStatus = Dr["CurrentStatus"].ToString();
else
obj.CurrentStatus = "";
objList.Add(obj);
}
}
return objList;
}
The exact error is:
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'OVER'.
Please look my full code...
Your ROW_NUMBER-"column" comes after the JOINs.
Change it to:
string sql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
Now use sql = String.Format(sql, orderBy, filter, rnStart, rnEnd) to assign the values.
The variables could be:
string orderBy = "ModelNumber ASC";
string filter = "BrandName = 'Sony'";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
Update: to show the complete method (at least the relevant code) according to your edit.
public MasterJobList GetListForGrid(int RecCount, int PageNo, string OrderBy)
{
string strSql = #"
WITH TempTable AS
(
Select
JobDetails.JobCode,
JobDetails.CurrentStatus,
MasterModel.Name As ModelNumber,
MasterModel.Code As ModelCode,
MasterBrand.Code As BrandCode,
MasterBrand.Name As BrandName,
MasterDeviceType.Code As DeviceCode,
MasterDeviceType.Name As DType,
ROW_NUMBER() OVER (ORDER BY {0}) AS RowNumber
From JobDetails JobDetails
Inner Join MasterDeviceType
ON JobDetails.DType = MasterDeviceType.Code
Inner Join MasterBrand
ON JobDetails.BCode = MasterBrand.Code
Inner join MasterModel
ON JobDetails.ModelNumber = MasterModel.Code,
WHERE {1}
)
SELECT * FROM TempTable WHERE RowNumber BETWEEN {2} AND {3}";
int rnStart = PageNo == 1 ? 1 : ((PageNo - 1) * RecCount) + 1;
int rnEnd = PageNo == 1 ? RecCount : PageNo * RecCount;
strSql = String.Format(strSql, OrderBy, "1=1", rnStart, rnEnd);
DataTable dt = objDB.GetDataTableFromSQL(strSql);
// ...
return objList;
}
please check this example in ssms and change the accordingly.
declare #t table(name varchar(50))
insert into #t values ('a'),('b'),('c'),('d'),('e')
select ROW_NUMBER() over ( order by name)
, name
from #t
Check the comment, you just apply the "orderby" by value
WITH temptable
AS (SELECT jobdetails.jobcode,
jobdetails.currentstatus,
mastermodel.NAME AS ModelNumber,
mastermodel.code AS ModelCode,
masterbrand.code AS BrandCode,
masterbrand.NAME AS BrandName,
masterdevicetype.code AS DeviceCode,
masterdevicetype.NAME AS DType,
Row_number()
OVER (
ORDER BY " + orderby + ") AS RowNumber --here you have to assign the order by value
FROM jobdetails JobDetails
INNER JOIN masterdevicetype
ON jobdetails.dtype = masterdevicetype.code
INNER JOIN masterbrand
ON jobdetails.bcode = masterbrand.code
INNER JOIN mastermodel
ON jobdetails.modelnumber = mastermodel.code
WHERE 1 = 1)
SELECT *
FROM temptable
WHERE rownumber BETWEEN {2} AND {3}