我使用 SQL Server 中的窗口聚合函数得到了这个查询。
SELECT customer,location, invoice_number, qty,
Sum(qty) OVER ( PARTITION BY customer,location) AS sub_total
FROM myTable
结果显示为
customer location invoice_number qty sub_total
479249 441 800002309 -8.00 -20.00
479249 441 800002310 -4.00 -20.00
479249 441 800002311 -8.00 -20.00
481439 441 800003344 -1.00 -1.00
483553 441 800003001 -8.00 -19.50
483553 441 800003001 -8.00 -19.50
483553 441 800003001 -3.50 -19.50
但我希望它将重复小计隐藏为
customer location invoice_number qty sub_total
479249 441 800002309 -8.00
479249 441 800002310 -4.00
479249 441 800002311 -8.00 -20.00
481439 441 800003344 -1.00 -1.00
483553 441 800003001 -8.00
483553 441 800003001 -8.00
483553 441 800003001 -3.50 -19.50
我怎样才能做到这一点?
最佳答案
您可以使用复杂的 case
语句来做到这一点:
SELECT customer, location, invoice_number, qty,
(case when row_number() over (partition by customer, location order by invoice_number desc) = 1
then Sum(qty) over (partition by customer, location)end) AS sub_total
FROM myTable
ORDER BY customer, location, invoice_number;
最后的ORDER BY
很重要。 SQL 结果集表示没有 ORDER BY
的无序集。数据可能看起来顺序正确,但除非明确声明,否则不一定正确。
关于SQL 窗口聚合函数隐藏重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41023612/