SQL 窗口聚合函数隐藏重复值

标签 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

我怎样才能做到这一点?

最佳答案

您可以使用复杂的 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/

相关文章:

sql - 在 Redshift 中使用 DISTINCT 的 listagg

sql - 如何将smalldatetime分解为年、月、日索引?

sql - 如何使用日历规则在 SQL 中获取一年中的一周?

sql - 组合 SUM 和 CASE 返回 0?

sql-server - 如何通过存储过程执行数据库中的所有 View

c# - Entity Framework 在指定 MaxLength 时使用 nvarchar (max)

c# - 如何防止用户生成的 SQL 查询中的 SQL 注入(inject)

sql - 并排加入两个查询

mysql - 返回表sql的函数

SQL查询行需要动态转换为列