我有一张这样的桌子:
Date Document No. Item Quantity Price
1/2/2019 1 ADUKU SS 1 1450
1/2/2019 1 AL GUIDE 1 250
1/2/2019 2 AL FLAT 1 75.65
1/2/2019 2 BATTERY(SMALL) 2 7.52
1/2/2019 2 Item 2 2 72.15
1/2/2019 2 Item3 2 58.75
1/6/2019 3 PAPER WHITE 0.25 1250
我需要这样的输出以及小计:
Date Document No. Item Quantity Price
1/2/2019 1 ADUKU SS 1 1450
1/2/2019 1 AL GUIDE 1 250
1/2/2019 2 AL FLAT 1" 3 MM 1 75.65
1/2/2019 2 BATTERY 2 7.52
1/2/2019 2 Item 2 2 72.15
1/2/2019 2 Item3 2 58.75
1/2/2019 Subtotal 1914.07
1/6/2019 3 PAPER WHITE 0.25 1250
1/6/2019 Subtotal 1250
如何使用sql查询获得所需的输出?
我需要根据日期进行小计。
到目前为止,我尝试的方法如下:
SELECT T0.[DocDate] AS 'Date', T1.[DocNum] AS 'Document No', T0.[Dscription] AS 'Item',
T0.[Quantity] AS 'Quantity', T0.[StockPrice] AS 'Inventory Price'
FROM [table_1] T0
INNER JOIN [table_2] T1
ON T1.[DocEntry] = T0.[DocEntry]
UNION ALL
SELECT T1.[DocDate] as 'Date', NULL,NULL,NULL, SUM(T0.StockPrice)
FROM [table_1] T0
INNER JOIN [table_2] T1
ON T1.[DocEntry] = T0.[DocEntry]
GROUP BY T1.[DocDate]
答案 0 :(得分:0)
您可以对表和总和使用UNION:
select *
from documents
union all
select
date,
null documentno,
'Subtotal' item,
null quantity,
sum(price) price
from documents
group by date
order by
date,
case when documentno is null then 1 else 0 end,
documentno
请参见demo
答案 1 :(得分:0)
语法表明这不是MySQL查询。假设使用SQL Server(与方括号一致),您可以使用grouping sets
,但是您需要一个聚合查询:
SELECT T1.DocDate, T1.DocNum, T2.Dscription AS Item,
SUM(T1.Quantity) AS Quantity,
T1.StockPrice AS InventoryPrice
FROM [table_1] T1 INNER JOIN
[table_2] T2
ON T2.[DocEntry] = T1.[DocEntry]
GROUP BY GROUPING SETS ( (T1.DocDate, T1.DocNum, T2.Dscription), (T1.DocDate, T2.Dscription) );