查询SQL Server时出错

时间:2014-02-12 09:36:18

标签: sql sql-server

这是我的表

create table #t(id int, amt int)

insert into #t values(1, 40), (1, 20), (1, 10), (2, 100), (2, 120), (2, 400)

我需要这样的输出!

id  amt
1    70
1    70
1    70
2    620
2    620
2    620

我试过

SELECT
    id, SUM(amt) 
FROM
    #t 
GROUP BY
    id 

3 个答案:

答案 0 :(得分:3)

试试这个!

select id,sum(amt) over(partition by id) as amt from #t

答案 1 :(得分:2)

select  id
,       sum(amt) over (partition by id)
from    #t

Example at SQL Fiddle.

答案 2 :(得分:1)

select a.id, c.amt from #t as a
left outer join 
(SELECT b.id, SUM(b.amt) as amt FROM   #t as b  GROUP BY  id ) as c on c.id=a.id