我想像这样显示我的数据
Name Product Amount Total
_______________________________________________
John Smith Burger 60.00 100.00
John Smith Fries 40.00
Michael Smith Burger 60.00 60.00
答案 0 :(得分:2)
您没有提及您的DBMS,因此这是ANSI标准SQL:
select name, product, amount,
case
when row_Number() over (partition by name order by ????) = 1 then
sum(amount) over (partition by name)
end as total
from the_table
order by name, ???;
请注意,没有"第一行"在关系数据库中。要识别第一个,您需要一个定义订单的列,并且可以用于order by
。您需要将???
替换为表格中的该列
答案 1 :(得分:0)
你可以使用窗口函数执行此操作,但您必须非常小心。问题是结果的排序和第一行的定义。
让我尝试使用name
,amount
和product
进行稳定排序:
select name, amount, product,
(case when row_number() over (partition by name order by amount desc, product) = 1
then sum(amount) over (partition by name)
end) as total
from t
order by name, amount desc, product;
在外部查询和窗口函数中使用相同的order by
键非常重要。