表格中的PARTIAL SUM

时间:2016-08-03 13:37:13

标签: tsql

我跟着表:

2016-01       111.00       100.00
2016-01       111.00        11.00
2016-02       222.00       100.00
2016-02       222.00       100.00
2016-02       222.00        22.00
2016-01       333.00       200.00
2016-01       333.00       133.00

我需要:

2016-01      444.00
2016-02      222.00

我如何收到这些数据?按期间求和,但只有不同的值?

3 个答案:

答案 0 :(得分:2)

USE SUM()DISTINCT

SELECT DateColName ,SUM(DISTINCT ColName)
FROM TABLENAME
GROUP BY DateColName 

答案 1 :(得分:1)

SUM() + DISTINCT + GROUP BY是您的朋友。

重新创建测试用例:

sqlite> CREATE TABLE money(month TEXT, q1 FLOAT, q2 FLOAT);
sqlite> INSERT INTO money VALUES('2016-01','111.00','100.00');
sqlite> INSERT INTO money VALUES('2016-01','111.00','11.00');
sqlite> INSERT INTO money VALUES('2016-02','222.00','100.00');
sqlite> INSERT INTO money VALUES('2016-02','222.00','100.00');
sqlite> INSERT INTO money VALUES('2016-02','222.00','22.00');
sqlite> INSERT INTO money VALUES('2016-01','333.00','200.00');
sqlite> INSERT INTO money VALUES('2016-01','333.00','133.00');

检查数据与您的数据相同:

sqlite> SELECT * FROM money;
2016-01|111.0|100.0
2016-01|111.0|11.0
2016-02|222.0|100.0
2016-02|222.0|100.0
2016-02|222.0|22.0
2016-01|333.0|200.0
2016-01|333.0|133.0

运行查询:

sqlite> SELECT month, SUM(DISTINCT q1) FROM money GROUP BY month;
2016-01|444.0
2016-02|222.0

答案 2 :(得分:0)

;with cte
as
(select
date,col1,col2
,row_number() over (partition by date,col1 order by date) as rownum
)
select 
date,sum(col1)
from cte 
where rownum=1
group by date