안녕하세요.
월별 누적 SQL을 어찌 풀어야 할지 고민되네요.
원천 Data는 다음과 같습니다.
기준년월 | 고객구분 | 매출금액
201601 | 사람1 | 100
201604 | 사람1 | 300
201607 | 사람1 | 500
201612 | 사람1 | 50
의 데이터를
기준년월|고객구분|당월매출금액|당년누적매출금액
201601 | 사람1 | 100 | 100
201602 | 사람1 | 0 | 100
201603 | 사람1 | 0 | 100
201604 | 사람1 | 300 | 400
201605 | 사람1 | 0 | 400
201606 | 사람1 | 0 | 400
201607 | 사람1 | 500 | 900
201608 | 사람1 | 0 | 900
201609 | 사람1 | 0 | 900
201610 | 사람1 | 0 | 900
201611 | 사람1 | 0 | 900
201612 | 사람1 | 50 | 950
의 결과와 같이 Sql을 어찌 풀어야 할까요?
Ms Sql 2008 입니다.
감사합니다.
Comment 3
-
Terry
2016.12.02 17:34
-
안산님아
2016.12.05 09:07
정말 감사 합니다. ^^*
-
항해자™
2016.12.06 16:14
그냥 풀어봤습니다,,,
;with cteSummary (cYear, cName, cAmount) as ( select 201601, '사람1', 100 union all select 201604, '사람1', 300 union all select 201607, '사람1', 500 union all select 201612, '사람1', 50 ) , cteYearList as ( select top 12 convert(char(6),dateadd(month,number,'2016-01-01'),112) as cYear from master.dbo.spt_values where number >= 0 group by number order by number ) select a.cYear , c.cName , isnull(b.cAmount,0) as cAmount , c.cTotal from cteYearList as a outer apply ( select cName , sum(cAmount) as cAmount from cteSummary as x where x.cYear = a.cYear group by cName ) as b outer apply ( select cName , sum(cAmount) as cTotal from cteSummary as x where x.cYear <= a.cYear group by cName ) as c go
하기 쿼리 참고하세요..
---쿼리시작---
;with tblA(기준년월,고객구분,매출금액) As
(
Select '201601','사람1',100 Union All
Select '201604','사람1',300 Union All
Select '201607','사람1',500 Union All
Select '201612','사람1',50
)
,tblB(년월,사람) As
(
Select Convert(char(6),Left(a.기준년월,4) + '01')
,a.고객구분
From tblA a
Group By LEFT(a.기준년월,4)
,a.고객구분
Union All
Select Convert(char(6)
, Left(a.년월,4)
+ ( Case When CONVERT(integer,Right(a.년월,2)) + 1 < 10 Then '0'
When CONVERT(integer,Right(a.년월,2)) + 1 >= 10 Then ''
End
)
+ Rtrim(Convert(char(2),CONVERT(integer,Right(a.년월,2)) + 1)))
,사람
From tblB a
Where CONVERT(integer,Right(a.년월,2)) <= 11
)
Select a.년월
,a.사람
,ISNULL(b.매출금액,0) As 당월매출금액
,IsNull(Sum(c.매출금액),0) As 당년누적매출금액
From tblB a
Left Outer Join
tblA b
On a.년월 = b.기준년월
And a.사람 = b.고객구분
Left Outer Join
tblA c
On a.년월 >= c.기준년월
And LEFT(a.년월,4) = LEFT(c.기준년월,4)
And a.사람 = c.고객구분
Group By a.년월
,a.사람
,b.매출금액
---쿼리끝---