SQL Window聚合函数隐藏重复值

时间:2016-12-07 17:21:40

标签: sql sql-server

我在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

我该怎么做?

1 个答案:

答案 0 :(得分:6)

您可以使用复杂的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无序集。数据看起来可能是正确的顺序,但除非明确声明,否则不一定正确。