简体   繁体   中英

How do you sum each row using multiple columns with SQL without it aggregating data?

I'm running my query below to pull out data and there are 3 columns I'm looking to SUM. However, it aggregates the data into one output instead of outputting it for each row it pulled from.

See the second select statement, how do I separate the data?

SELECT a.RTL_TRAN_ID, b.LINEITM_SEQ, b.BEGIN_DATE_TIMESTAMP, b.ITEM_ID, b.ITEM_STYLE_ID, b.ITEM_QUANTITY, b.ITEM_BASE_UNIT_PRICE, b.ITEM_UNIT_PRICE, b.ITEM_EXTENDED_AMT, x.RTL_LOC_ID
FROM CMP_PROMO_TRAN_RESULT AS a
JOIN TRN_LINE_ITEM AS b
ON a.RTL_TRAN_ID = b.RTL_TRANS_ID
JOIN TRN_TRANSACTION AS x 
ON x.RTL_TRANS_ID = a.RTL_TRAN_ID
WHERE a.PROMOTION_ID IN (51)
AND b.lineitm_typcode = 'sale'
AND b.item_base_unit_price <> b.item_unit_price
ORDER BY a.RTL_TRAN_ID

SELECT 
SUM(b.ITEM_QUANTITY) * SUM(b.ITEM_BASE_UNIT_PRICE) - SUM(b.ITEM_EXTENDED_AMT) 
AS 'Discount Given' 
FROM CMP_PROMO_TRAN_RESULT AS a
JOIN TRN_LINE_ITEM AS b 
ON a.RTL_TRAN_ID = b.RTL_TRANS_ID
WHERE a.PROMOTION_ID IN (51) 

If you use SUM() , you are telling MySQL to aggregate data of the same group into one number. There will be an implicit GROUP BY added if you don't already one.

In your case, it seems like you do NOT want to aggregate. Then you should rewrite your query to something like this (ie just drop the SUM() aggregation).

Updated query (with more columns supporting debugging)

SELECT 
    b.ITEM_QUANTITY
    , b.ITEM_BASE_UNIT_PRICE
    , b.ITEM_EXTENDED_AMT 
    , b.ITEM_QUANTITY * b.ITEM_BASE_UNIT_PRICE - b.ITEM_EXTENDED_AMT 
        AS 'Discount Given' 
FROM 
    CMP_PROMO_TRAN_RESULT AS a
    JOIN TRN_LINE_ITEM AS b 
        ON a.RTL_TRAN_ID = b.RTL_TRANS_ID
WHERE a.PROMOTION_ID IN (51) 

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