日期:2014-05-17  浏览次数:20387 次

求个 MSSQL 统计方法。
id         state       times
------------------------------
a          1           0
a          0           13
a          1           0
a          0           46
b          0           566
b          1           0
b          0           15
c          1           0
c          0           480
d          0           960
d          1           0
d          0           90
------------------------------

想要得到的结果
--------------------------------
a       59
b       15
c       480
d       90
--------------------------------

就是 group by id 之后 每个 id 第一条 state 不等于 0 的 sum(times)

数据量在 35W + 
MS?SQL 统计

------解决方案--------------------
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (id nvarchar(2),state int,times int)
insert into [TB]
select 'a',1,0 union all
select 'a',0,13 union all
select 'a',1,0 union all
select 'a',0,46 union all
select 'b',0,566 union all
select 'b',1,0 union all
select 'b',0,15 union all
select 'c',1,0 union all
select 'c',0,480 union all
select 'd',0,960 union all
select 'd',1,0 union all
select 'd',0,90

select * from [TB]

SELECT  id ,
        SUM(CASE WHEN STATE = 0
                     &nbs