I need help to SUM and MULTIPLIES on join 2 tables:
tb1
tb2
In tb1
, I need to sum QTY
and multiples SKU
with PRICE
without repeating same SKU
(21135208
, 21035621
):
Current query:
x
SELECT
tb1.DOC_NO,
CAST(SUM(tb2.QTY) AS FLOAT) AS QTY_TOTAL,
ROUND(CAST(SUM(tb2.QTY * tb2.PRICE) AS FLOAT), 2) AS PRICE_TOTAL,
tb1.DATE,
tb1.STATUS_A,
tb2.STATUS_B
FROM
tb1
INNER JOIN
tb2 ON tb1.DOC_NO = tb2.DOC_NO
WHERE
tb1.STATUS_B = '0'
GROUP BY
tb1.DOC_NO, tb1.DATE,
tb1.STATUS_A, tb1.STATUS_B
ORDER BY
COH.DOC_NO_REQ_TO_ULI DESC
My result is:
Expected result is:
Advertisement
Answer
I believe that you could filter out duplicates by using a subquery like SELECT DISTINCT ... FROM tb1
, while leaving the rest of the query untouched:
SELECT
tb0.DOC_NO,
CAST ( SUM ( tb2.QTY ) AS FLOAT ) AS QTY_TOTAL,
ROUND( CAST ( SUM ( tb2.QTY * tb2.PRICE ) AS FLOAT ), 2) AS PRICE_TOTAL,
tb0.DATE,
tb2.STATUS_A,
tb2.STATUS_B
FROM
(SELECT DISTINCT DOC_NO, CM, SKU, PRICE, QTY, DATE FROM tb1) AS tb0
INNER JOIN tb2 ON tb0.DOC_NO = tb2.DOC_NO
WHERE
tb2.STATUS_B = '0'
GROUP BY
tb0.DOC_NO,
tb0.DATE,
tb2.STATUS_A,
tb2.STATUS_B
ORDER BY
COH.DOC_NO_REQ_TO_ULI DESC
NB: there are some issues with the table aliases in your query:
- columns
STATUS_A
orSTATUS_B
should be prefixedtb2
, nottb1
(I fixed that) - alias
COH
which is being used in theORDER BY
clause is not declared anywhere in the query (that’s a syntax error)