如何有条件地求和?

时间:2013-03-08 19:46:06

标签: sql-server group-by sum

我有一张下表

Col1   Col2   Col3
A1     1      null
A1     2      null
B1     5      null
B2     6      null
M1     1      M
M2     2      M
M3     3      M
J1     1      J
J2     2      J

我想根据Col1对Col2求和。查询将如下,

select Col1, sum (Col2)
group by Col1

但是,如果Col3有相同的字母,我想要为所有Col1总结Col2。所以结果表应该像

Col1    Col2 
A1      3
B1      5
B2      6
M1      6
M2      6
M3      6
J1      3
J2      3

如何更改查询以获取上表?

2 个答案:

答案 0 :(得分:1)

在评论/更新问题后进行修改。我不知道一个聪明的方式,看起来有些人虽然有一个。但

select * from (
select Col1, SUM(Col2) Col2
from Table
where Col3 is null
group by Col1

union

select mainset.Col1, tmp.Col2
from Table mainset
join 
(
    select Col3, SUM(Col2) Col2
    from Table
    where Col3 is not null
    group by Col3
) tmp on tmp.Col3 = mainset.Col3

where mainset.Col3 is not null
) fullset
order by fullset.Col1

答案 1 :(得分:0)

你可以这样做(我将表命名为#a):

    ;WITH col3Sum AS
    (
        SELECT Col3, SUM(Col2) SUM3
        FROM #a
        WHERE col3 IS NOT NULL
        GROUP BY col3
    ),
        col1Sum AS
    (
        SELECT Col1, SUM(Col2) sum1
        FROM #a 
        GROUP BY Col1
    )   
    SELECT c1.Col1, ISNULL(c3.SUM3, c1.sum1) AS Col2
    FROM col1Sum c1
    LEFT JOIN col3Sum c3
        ON c1.Col1 LIKE c3.Col3+'%'
    ORDER BY c1.Col1