如何在SQL Server的最后一行组中获取组的总和

时间:2016-11-21 20:17:07

标签: sql sql-server tsql

以下是我的示例数据:

ID  Prod  Price 
----------------
01  Vios  150
01  Vios  120
02  Copax 100
02  Copax 200

欲望结果是:

ID   Prod   Price  Total
------------------------
01  Vios    150        0
01  Vios    120      270
02  Copax   100        0
02  Copax   200      300

2 个答案:

答案 0 :(得分:0)

这可以通过任意决定最后一行 - "命令由Prod"在over子句中可以是任何东西。此外,每个ID中的价格顺序也是任意的 - 因此,如果重要的是100在200之前,那么您将需要一些其他字段来提供有意义的订单

create table #data
(
    ID int,
    Prod varchar(5),
    Price int
);

insert into #data values(1,'Vios',150);
insert into #data values(1,'Vios',120);
insert into #data values(2,'Copax',100);
insert into #data values(2,'Copax',200);

with cte as (
    select ID, 
        Prod, 
        Price,
        ROW_NUMBER() over (partition by ID order by Prod) rn,
        sum(Price) over (partition by ID order by Prod) total
    from #data
)
select ID,
    Prod,
    Price,
    case when rn = 1 then total else 0 end
from cte
order by ID,
    rn desc

答案 1 :(得分:0)

android update sdk --no-ui --all --filter "build-tools-24.0.2"

结果集

ID          Prod  Price       Total
----------- ----- ----------- -----------
1           Vios  150         150
1           Vios  120         270
2           Copax 100         100
2           Copax 200         300