-10
我通過我得到的一些數據,現在下面多行合併成一個在SQL
col1 col2 col3 col4 col5 col6 col7
------------------------------------------------------------
SA106141 ABC test 1400 0 0 58800
SA106141 ABC test 1100 53963 54 54017
SA106141 ABC test 3000 141184 141 141325
SA106141 ABC test 2800 154548 155 154703
SA106141 ABC test 1500 79042 79 79121
SA106141 ABC test -9800 -487967 0 0
,但給定一個表所需的輸出應該是
col1 col2 col3 col4 col5 col6 col7
SA106141 ABC test 0 -59229 429 0
這是查詢我有到目前爲止:
SELECT DISTINCT
col1, col2, col3,
ISNULL(SUM(QTY), 0) AS col4,
ISNULL(SUM(NET_AMT), 0) AS col5,
ISNULL(SUM(STT), 0) AS col6,
CASE
WHEN ISNULL(SUM(grand_total), 0) <= 0
THEN 0
ELSE ISNULL(SUM(grand_total), 0)
END AS col7
FROM
(SELECT
Dates, TR_DT, TR_NO, SA, GRP, ID, SAID, Exch, Code,
Client, SCRIPT, BUYSELL, QTY, NT_RT, NET_AMT,
QTY * NT_RT AS New_Net_amt,STT,
ISNULL(NET_AMT + STT,QTY * NT_RT) AS grand_total,
CAST(SA + GRP + ID + SAID AS VARCHAR(50)) AS testid
FROM
testtable
GROUP BY
CAST (SA + GRP + ID + SAID AS VARCHAR(50)), Dates, TR_DT,
TR_NO, Exch, Code, Client, SCRIPT, BUYSELL, QTY,
NT_RT, NET_AMT, STT, SA, GRP, ID, SAID) t
GROUP BY
t.testid, t.Dates, t.Client, t.SCRIPT
ORDER BY
t.Client, t.testid, t.SCRIPT, t.Dates ASC
請幫
你能解釋一下組合行所需的邏輯嗎?另外,您目前查詢的問題究竟是什麼? – Mureinik
邏輯是col2有ABC的多條記錄我只需要單個ABC,col4和col4和col6和abc中col4的總和可以和多個用戶一樣測試1 test2,test3 soi需要一個查詢,顯示test1 abc col4 total col5 total col6 total –
查詢你粘貼的does not似乎與你在這裏解釋的邏輯有任何關係。該查詢中使用了更多的列! – Hybridzz