SQLserver 如何分组合计?
例如,有表名称列W_anme,数量列w_sl
W_anme w_sl
---------------------------
aa 3
bb 6
cc 2
aa 1
bb 8
bb 5
---------------------------
想得到
W_anme w_sl
---------------------------
aa 4
bb 19
cc 2
---------------------------
这个SQL语句怎么写?
[解决办法]
declare @t table (W_anme varchar(2),w_sl int)
insert into @t
select 'aa',3 union all
select 'bb',6 union all
select 'cc',2 union all
select 'aa',1 union all
select 'bb',8 union all
select 'bb',5
select W_anme,sum(w_sl) w_sl from @t group by W_anme
/*
W_anme w_sl
------ -----------
aa 4
bb 19
cc 2
*/
select W_anme,sum(w_sl) w_sl from 你的表名 group by W_anme
select id,w_anme,sum(w_sl) over(partition by w_anme) from tab
declare @t table (W_name varchar(2),w_sl INT, id INT)
insert into @t
select 'aa',3, 1 union all
select 'bb',6, 2 union all
select 'cc',2, 3 union all
select 'aa',1, 4 union all
select 'bb',8, 5 union all
select 'bb',5, 6
SELECT B.*, A.W_SL FROM
(SELECT W_name, w_sl=SUM(w_sl) FROM @t GROUP BY W_name) a
CROSS APPLY
(SELECT TOP(1) * FROM @t WHERE W_name = a.W_name ORDER BY id DESC) b --想取哪一条,自己随意