我有一张表,我现在可以通过它获取一些数据
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
请帮忙
答案 0 :(得分:0)
这是你在找什么?
select
col1, col2, col3,
sum(isnull(col4, 0)) col4,
sum(isnull(col5, 0)) col5,
sum(isnull(col6, 0)) col6,
sum(isnull(col7, 0)) col7
FROM
testtable
group by
col1, col2, col3