2016-12-07 11 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