这是一种在 sqlite 下模拟 rollup 的方法。我在数据库中偶然发现了 2007 年的答案forum http://www.daniweb.com/web-development/databases/ms-sql/threads/255430/results-with-subtotals-and-grandtotal询问小计和总计。我将在这里用我的简化案例进行总结。
我有一个股票表,其中包含 Ticker_Symbol(文本)、底层证券(文本)和数量(整数)等字段。对于这个例子来说这些就足够了。
可以使用 sqlite 中的以下调用来模拟 Rollup:
select Ticker_Symbol,Underlying,Quantity from (
select '1' orderCol, Ticker_Symbol,Underlying,Quantity from stocks
union
select '2' orderCol, Ticker_Symbol, 'Subtotal' as Underlying, Sum(Quantity) as Quantity from stocks
group by Ticker_Symbol
union
select '99' orderCol, '_' as Ticker_Symbol, 'GrandTotal' as Underlying, sum(Quantity) as Quantity from stocks)
as t1 order by case when orderCol=99 then 1 else 0 end, Ticker_Symbol, orderCol;
这会产生类似于下面的输出:
|Ticker_Symbol |Underlying|Quantity|
|-------------------|----------|--------|
AAPL AAPL 500
AAPL AAPL 1000
AAPL AAPL 2000
AAPL Subtotal 3500
AAPL140222P00500000 AAPL 10
AAPL140222P00500000 Subtotal 10
IBM140322C00180000 IBM 25
IBM140322C00180000 Subtotal 25
R140222C00067500 R 10
R140222C00067500 Subtotal 10
VLCCF VLCCF 300
VLCCF VLCCF 2000
VLCCF Subtotal 2300
_ GrandTotal 5845
不幸的是,我找不到避免使用 Ticker_Symbol 的方法。理想情况下,最好将当前的 Ticker_Symbol 替换为“Subtotal”(或 GrandTotal),但这不起作用。另请注意使用“_”以确保 GrandTotal 确实显示在最后一行。
我希望这对其他人有帮助,如果有人有更好的方法,请添加。