在sql中有sum值

时间:2016-09-13 12:28:37

标签: sql sql-server

假设以下样本数据:

a   |   b  |    c   |  d    |  e   |  f
-----------------------------------------
400 | 1200 |    1   | 500   |  1   |  200
400 | 1200 |    1   | 500   |  1   |  200
400 | 1200 |    1   | 500   |  1   |  200
400 | 1200 |    1   | 500   |  1   |  200
400 | 1200 |    2   | 300   |  3   |  300
400 | 1200 |    2   | 300   |  3   |  300
401 | 800  |    3   | 100   |  4   |  100
401 | 800  |    4   | 100   |  NULL|  NULL
402 | 300  |   NULL | NULL  |  NULL|  NULL

我希望我的输出包含a和b列的每个值的一个记录,以及不同c的列d的总和。所以,我的最终结果应该是这样的:

400 | 1200 | 800 | 500
400 | 800  | 200 | 100
401 | 300  | NULL| NULL

在SQL中是否有任何具体的声明?

4 个答案:

答案 0 :(得分:0)

Sum汇总与Distinct

一起使用
select a,b,sum(distinct d),sum(distinct f) 
From yourtable
Group by a,b

答案 1 :(得分:0)

以下查询返回您的预期结果:

SELECT a, b, SUM(Dval) AS d
FROM (
    SELECT a, b, c, SUM(DISTINCT d) Dval
    FROM Testtable
    GROUP BY a, b, c
) R
GROUP BY a, b
ORDER BY a

使用样本数据实际执行:

DECLARE @Testtable TABLE (a INT, b INT, c INT, d INT);

INSERT INTO @Testtable (a, b, c, d) VALUES 
(400, 1200, 1, 500),
(400, 1200, 1, 500),
(400, 1200, 1, 500),
(400, 1200, 1, 500),
(400, 1200, 2, 300),
(400, 1200, 2, 300),
(401, 800 , 3, 100),
(401, 800 , 4, 100),
(402, 300 , NULL, NULL);

SELECT a, b, SUM(Dval) AS d
FROM (
    SELECT a, b, c, SUM(DISTINCT d) Dval
    FROM @Testtable
    GROUP BY a, b, c
) R
GROUP BY a, b
ORDER BY a

答案 2 :(得分:0)

此查询将为您提供所需的结果:

SELECT  a,
        SUM(DISTINCT b) b,
        SUM(d) d
FROM(
    SELECT DISTINCT a,
                    b,
                    c,
                    d
    FROM YourTable
    ) t
GROUP BY a

在子查询中,我们获得没有重复的行,然后是GROUP BY a with aggregation。

修改

对于您的新记录集 - 相同的规则:

SELECT  a,
        SUM(DISTINCT b) b,
        SUM(d) d,
        SUM(DISTINCT f) f
FROM(
    SELECT DISTINCT a,
                    b,
                    c,
                    d,
                    e,
                    f
    FROM YourTable
    ) t
GROUP BY a

输出:

a   b       d       f
400 1200    800     500
401 800     200     100
402 300     NULL    NULL

答案 3 :(得分:0)

select a,b,sum(f),d
from [table name]
where c>0
group by a,b,d