表格包含发票数据,我需要在不使用子查询的情况下,根据年份和方法总结数量和金额
表1:
╔════════╦═══════╦════════╦══════╗
║Month ║ Desc ║ Amt ║ QTy ║
╠════════╬═══════╬════════╬══════╬
║ 1 ║ FF ║ 25.00 ║ 1 ║
║ 1 ║ ss ║ 55.00 ║ 2 ║
║ 2 ║ ss ║ 78.00 ║ 3 ║
║ 2 ║ FF ║ 99.00 ║ 1 ║
║ 3 ║ ss ║ 54.00 ║ 1 ║
║ 4 ║ FF ║ 58.00 ║ 5 ║
║ 5 ║ FF ║ 55.00 ║ 2 ║
║ 5 ║ ss ║ 55.00 ║ 2 ║
║ 1 ║ ss ║ 77.00 ║ 1 ║
╚════════╩═══════╩════════╝══════╝
这就是我需要得到结果的方法
╔════════╦═══════╦════════╦══════╗══════╗
║Month ║yearamt║ Amt ║ QTy ║yerQty║
╠════════╬═══════╬════════╬══════╬══════╬
║ 1 ║ 556 ║ 157 ║ 3 ║ 9 ║
║ 2 ║ 556 ║ 177 ║ 3 ║ 9 ║
║ 3 ║ 556 ║ 54 ║ 1 ║ 9 ║
║ 4 ║ 556 ║ 58 ║null ║ 9 ║
║ 5 ║ 556 ║ 110 ║ 2 ║ 9 ║
╚════════╩═══════╩════════╝══════╝══════╝
在我当前的查询中,我无法获得yerQty列,任何解决方案或更好的方法来获得上述结果而不使用子查询
select invoicedate
,Sum(amount) over ( ) yearamoutn,Sum(amount))amount
case when DESC ='SS' and netamount <>0 then sum(Quantity) end as Quantity
from Table1 group by invoicedate,DESC
答案 0 :(得分:0)
尝试此解决方案
DECLARE @Table1 TABLE
([Month] int, [Desc] varchar(2), [Amt] int, [QTy] int)
;
INSERT INTO @Table1
([Month], [Desc], [Amt], [QTy])
VALUES
(1, 'FF', 25.00, 1),
(1, 'ss', 55.00, 2),
(2, 'ss', 78.00, 3),
(2, 'FF', 99.00, 1),
(3, 'ss', 54.00, 1),
(4, 'FF', 58.00, 5),
(5, 'FF', 55.00, 2),
(5, 'ss', 55.00, 2),
(1, 'ss', 77.00, 1)
;
SELECT DISTINCT
[Month],
YearAmt = SUM([Amt]) OVER(PARTITION BY 1),
Amt = SUM([Amt]) OVER(PARTITION BY [MOnth]),
Qty = SUM(CASE [Desc] WHEN 'SS' THEN [QTy] ELSE 0 END) OVER(PARTITION BY [MOnth]),
YearQty = SUM(CASE [Desc] WHEN 'SS' THEN [QTy] ELSE 0 END) OVER(PARTITION BY 1)
FROM @Table1
我的结果