每组之前的原始数据

时间:2016-09-07 11:39:28

标签: sql sql-server-2008-r2 group-by rollup

我应该执行哪些查询才能逐行显示原始数据?有没有办法做到这一点?

User   ReceiptNo   Price
-----  ----------  ------
A      876         100
A      877          50
                   **150**
B      960          60
B      961          40
                   **100**

2 个答案:

答案 0 :(得分:1)

大多数数据库都支持标准组,例如rollupgrouping sets等修饰符。如果是这样,你可以这样做:

select user, receiptno, sum(price) as price
from t
group by grouping sets ((user, receiptno), (user));

答案 1 :(得分:0)

select user, receiptno, price, 1 as order_column 
from t
union all
select user, '' as receiptno, sum(price) as price, 2 as order_column 
from t
group by user

order by user, order_column

您可以将结果与原始数据结合,并添加要在ORDER BY中使用的人工列,以将聚合行放在组的末尾(在原始数据之后)。