2016-12-07 12 views
2

SQL Serverのウィンドウ集計関数を使用してこのクエリを取得しました。繰り返し値を隠すSQLウィンドウ集計関数

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 

として繰り返し小計を非表示にしたいですか?

答えて

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なしです。データは正しい順序であるように見えるかもしれませんが、明示的に宣言されない限り、必ずしも真ではありません。

+0

おかげで、 'over'に' partition by'を追加しました。 – Shawn

関連する問題