ID |
판매날짜 |
판매금액 |
1 |
2013-10-11 |
1000 |
2 |
2013-10-12 |
2000 |
1 |
2013-11-01 |
1000 |
2 |
2013-10-13 |
2000 |
3 |
2013-10-20 |
1000 |
4 |
2013-10-21 |
1000 |
3 |
2013-10-20 |
2000 |
2 |
2013-11-11 |
1000 |
1 |
2013-11-22 |
2000 |
결과
ID=1인 것중에 판매금액 월별 합 출력
ID |
월 |
합계 |
1 |
1 |
0 |
1 |
2 |
0 |
1 |
3 |
0 |
1 |
4 |
0 |
1 |
5 |
0 |
1 |
6 |
0 |
1 |
7 |
0 |
1 |
8 |
0 |
1 |
9 |
0 |
1 |
10 |
1000 |
1 |
11 |
3000 |
1 |
12 |
0 |
위와 같은 결과를 뽑고싶습니다.
왕초보입니다. ㅜㅜ
Comment 3
-
catchv
2013.11.22 08:41
-
군고구마
2013.11.25 16:13
CREATE TABLE SALE_LOG(ID INT,SALE_DATE CHAR(10),Amount INT)GOINSERT INTO SALE_LOG VALUES(1,'2013-10-11',1000)INSERT INTO SALE_LOG VALUES(2,'2013-10-12',2000)INSERT INTO SALE_LOG VALUES(1,'2013-11-01',1000)INSERT INTO SALE_LOG VALUES(2,'2013-10-13',2000)INSERT INTO SALE_LOG VALUES(3,'2013-10-20',1000)INSERT INTO SALE_LOG VALUES(4,'2013-10-21',1000)INSERT INTO SALE_LOG VALUES(3,'2013-10-20',2000)INSERT INTO SALE_LOG VALUES(2,'2013-11-11',1000)INSERT INTO SALE_LOG VALUES(1,'2013-11-22',2000)GOSELECT * FROM SALE_LOGGOCREATE PROC SALE_PROC@ID INTASSET NOCOUNT ONSELECT ID,DATEPART(month,SALE_DATE),SUM(Amount)FROM DBO.SALE_LOG WITH(NOLOCK)WHERE ID = @IDGROUP BY ID,DATEPART(month,SALE_DATE)GO -
한태
2016.03.21 21:26
CREATE TABLE SALE_LOG(ID INT,SALE_DATE CHAR(10),Amount INT)GOINSERT INTO SALE_LOG VALUES(1,'2013-10-11',1000)INSERT INTO SALE_LOG VALUES(2,'2013-10-12',2000)INSERT INTO SALE_LOG VALUES(1,'2013-11-01',1000)INSERT INTO SALE_LOG VALUES(2,'2013-10-13',2000)INSERT INTO SALE_LOG VALUES(3,'2013-10-20',1000)INSERT INTO SALE_LOG VALUES(4,'2013-10-21',1000)INSERT INTO SALE_LOG VALUES(3,'2013-10-20',2000)INSERT INTO SALE_LOG VALUES(2,'2013-11-11',1000)INSERT INTO SALE_LOG VALUES(1,'2013-11-22',2000)GO;WITH t AS(SELECT DATEADD(yy, DATEDIFF(yy, 0, '2013-01-01'), 0) dt, 1 xUNION ALLSELECT DATEADD(mm,1,dt),x+1FROM tWHERE x +1 < 13)select isnull(b.id,1) as ID, a.dt as 월, isnull(b.sa, 0) as 합계from t a left outer join(select id, DATEPART(month , sale_date) AS sale_date, SUM(amount) safrom sale_logwhere ID = 1GROUP BY ID, DATEPART(month , sale_date) ) bON b.sale_date=DATEPART(month , a.dt)2013년 달력을 임시테이블로 만들어 판매에 속하지 않은 달도 표현하였습니다.달력테이블이 하나쯤 있으면 쿼리를 작성하기에 유용하다고 하는데 이번 경우를 통해 알 수 있었습니다.
DATEPART(month , 판매날짜) AS [월]
SUM(판매금액) AS [합계]
ID = 1
GROUP BY ID, DATEPART(month , 판매날짜)
참고 하시면 될 것 같습니다.