每组前的原始数据

Raw data before each group by

我应该执行哪些查询才能在每组前按行显示原始数据?有办法吗?

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

大多数数据库支持标准的分组方式,如 rollupgrouping sets。如果是这样,你可以这样做:

select user, receiptno, sum(price) as price
from t
group by grouping sets ((user, receiptno), (user));
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 中使用,以将聚合行放在组的末尾(在原始数据之后)。