3

我有一张下表

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

如何更改我的查询以获取上述表格?

4

2 回答 2

1

Edit after comment / update to question. I didn't know a clever way, seems like some others have one though.

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
于 2013-03-08T19:53:20.553 回答
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
于 2013-03-08T20:18:03.463 回答