Skip to content
Advertisement

SQL Server : sum and multiplies on 2 tables

I need help to SUM and MULTIPLIES on join 2 tables:

tb1

Tabel 1

tb2

Tabel 2

In tb1, I need to sum QTY and multiples SKU with PRICE without repeating same SKU (21135208, 21035621):

Current query:

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:

enter image description here

Expected result is:

enter image description here

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 or STATUS_B should be prefixed tb2, not tb1 (I fixed that)
  • alias COH which is being used in the ORDER BY clause is not declared anywhere in the query (that’s a syntax error)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement