简体   繁体   中英

SQL Server : sum and multiplies on 2 tables

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

tb1

表 1

tb2

表 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:

在此处输入图片说明

Expected result is:

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM