【问题标题】:SQL Get subtotal in each groupSQL 获取每个组中的小计
【发布时间】:2018-11-27 08:06:37
【问题描述】:

在我的时区早上好

我的目标是:

TYPE |  CODE | PRICE | QUANTITY
A       10      34       1
A       11      20       2
A       15      17       2
A       Total   71       5
B       13      14       1
B       10      24       2
B      Total    38       3

我使用的是 Sybase ASE 15.5 版,因此没有 ROLLUP 或 CUBE 运算符。 光标是我唯一的方法吗?

提前致谢 最好的问候

【问题讨论】:

    标签: sql group-by sap-ase subtotal


    【解决方案1】:

    您可以将这样的 SQL 语句与 union all 一起使用(排序对于您的目标很重要):

    select q.*
      from
      (
        select type, cast(code as char(5)) as code, price, quantity
          from tab
        union all
        select type, 'Total', sum(price), sum(quantity) 
          from tab
        group by type
      ) q
      order by type, code
    

    我在 SQL Server 中添加了 Demo,但语法对两者都适用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多