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可以做到这一点吗?
一种选择是 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