SQL查询:没有聚合函数时如何创建小计行

时间:2019-06-30 19:00:35

标签: sql sql-server

SQL中是否有一个可以显示小计行的函数。我有一张这样的桌子:

Date    INVNUNBER     CUSTOMER     ITEM     QTY     SALES
20190630 IN3343       joe's comp   23225    2.0     3000
20190630 IN3343       joe's comp   23214    1.0     400
20190630 IN3353       matt's comp. 12222     3.0     6000
20190630 IN3353       matt's comp. 32222     3.0     3000 

我尝试了ROLLUP,但是好像ROLLUP需要一个聚合函数,在这里我必须对一个字段求​​和,所有其他字段都需要放在Group By子句中,但是我实际上并不需要任何东西分组:

我尝试过:

SELECT DATE, INVNUMBER, CUSTOMER, ITEM, QUANTITY, SALES
FROM OESHDT
WHERE DATE = '20190630'
GROUP BY DATE, INVNUMBER, CUSTOMER WITH ROLLUP

然后我得到:

  

在选择列表中,'OESHDT.ITEM'列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

我只想这样获得每个发票编号的小计:

Date    INVNUNBER     CUSTOMER     ITEM     QTY     SALES
20190630 IN3343       joe's comp   23225    2.0     3000
20190630 IN3343       joe's comp   23214    1.0     400
                                           3.0     3400
20190630 IN3353       matt's comp. 12222     3.0     6000
20190630 IN3353       matt's comp. 32222     3.0     3000 
                                             6.0    9000

由于我没有汇总任何内容,我只希望每个分类汇总,因此SQL可以做到吗?

1 个答案:

答案 0 :(得分:5)

一个选项是Grouping Sets

示例

Declare @YourTable Table ([Date] varchar(50),[INVNUNBER] varchar(50),[CUSTOMER] varchar(50),[ITEM] varchar(50),[QTY] int,[SALES] int)
Insert Into @YourTable Values 
 (20190630,'IN3343','joe''s comp',23225,2.0,3000)
,(20190630,'IN3343','joe''s comp',23214,1.0,400)
,(20190630,'IN3353','matt''s comp.',12222,3.0,6000)
,(20190630,'IN3353','matt''s comp.',32222,3.0,3000)

Select Date
      ,InvNunber
      ,Customer
      ,Item
      ,Qty  = sum(Qty)
      ,Sales = sum(Sales)
 From  @YourTable
 Group By 
   Grouping Sets (
                    (Date,InvNunber,Customer,Item)
                   ,(Date,InvNunber)
                   ,(left(Date,0))
                 )
  Order By left(Date,0) Desc
          ,Date
          ,InvNunber
          ,Customer Desc

返回

Date    InvNunber   Customer        Item    Qty Sales
20190630    IN3343  joe's comp      23214   1   400
20190630    IN3343  joe's comp      23225   2   3000
20190630    IN3343  NULL            NULL    3   3400
20190630    IN3353  matt's comp.    12222   3   6000
20190630    IN3353  matt's comp.    32222   3   3000
20190630    IN3353  NULL            NULL    6   9000
NULL        NULL    NULL            NULL    9   12400