데이터베이스 개발자 질문과 답변 게시판
데이터베이스 개발/운영 관련 질문과 답변을 올리는 게시판입니다. 궁금하신 내용을 이곳에서 문의하시면 SQLER 분들의 답변을 받으실 수 있습니다. 문의를 하실때에는 최근 작업하신 특이 사항이나, 장애 발생 전 상황을 상세히 올려 주시면 답글을 적어주시는 SQLER분들의 답변이 더 정확할 수 있으니 도움 되시길 바랍니다. 쿼리 문의일 경우, 실제 문제가 재현되는 테이블생성, 샘플데이터 생성 쿼리를 함께 올려 주시면 더 빠르고 정확한 쿼리 문의 응답이 가능합니다.
안녕하세요
생 초보 입니다.
일하는 중에 쓸일이 있어서 덜컥 이런 쿼리를 받았습니다.
select Datepart(day,dateAdd(hour,0,a.ObservanceTime)) as '일자', sum(a.ObservanceCount) as 'X'
from Observances a, SecurityChecks b
where a.ObservanceType=1
and a.SecChkID=b.SecChkID
and b.tagname like 'X%'
and observancetime between '2015-10-01 00:00:00' and '2015-10-31 23:59:59'
group by Datepart(day,dateAdd(hour,0,ObservanceTime))
order by '일자'
결과
일자 X
1 135
2 189
3 999
4 789
5 456
6 123
7 456
8 789
....
31 777
select Datepart(day,dateAdd(hour,0,a.ObservanceTime)) as '일자', sum(a.ObservanceCount) as 'Y'
from Observances a, SecurityChecks b
where a.ObservanceType=1
and a.SecChkID=b.SecChkID
and b.tagname like 'Y%'
and observancetime between '2015-10-01 00:00:00' and '2015-10-31 23:59:59'
group by Datepart(day,dateAdd(hour,0,ObservanceTime))
order by '일자'
결과 2
일자 Y
1 195
3 164
4 788
31 70
1 195
3 164
4 788
31 70
select Datepart(day,dateAdd(hour,0,a.ObservanceTime)) as '일자', sum(a.ObservanceCount) as 'Z'
from Observances a, SecurityChecks b
where a.ObservanceType=1
and a.SecChkID=b.SecChkID
and b.tagname like 'Z%'
and observancetime between '2015-10-01 00:00:00' and '2015-10-31 23:59:59'
group by Datepart(day,dateAdd(hour,0,ObservanceTime))
order by '일자'
결과 3
일자 Z
1 13
1 13
요런 아이들이 수십개 되는데요 ㅠㅠ
해당 결과값을 아래처럼 나타내고 싶은데 SELF JOIN 이나 UNION 같은 것들로 해결해 보려고
인터넷 여기저기를 돌아봤지만 해결이 안됩니다 ㅠㅠ
일자 X Y Z
1 135 195 13
2 189 0 0
3 999 164 0
4 789 788 0
5 456 0 0
6 123 0 0
7 456 0 0
8 789 0 0
....
31 777 70 0
2 189 0 0
3 999 164 0
4 789 788 0
5 456 0 0
6 123 0 0
7 456 0 0
8 789 0 0
....
31 777 70 0
고견을 기다리겠습니다 ㅠㅠ
case when을 이용하시면
select Datepart(day,dateAdd(hour,0,a.ObservanceTime)) as '일자'
, sum(case when b.tagname like 'X%' then a.ObservanceCount else 0 end ) as 'X'
, sum(case when b.tagname like 'Y%' then a.ObservanceCount else 0 end ) as 'Y'
, sum(case when b.tagname like 'Z%' then a.ObservanceCount else 0 end ) as 'Z'
from Observances a, SecurityChecks b
where a.ObservanceType=1
and a.SecChkID=b.SecChkID
and observancetime between '2015-10-01 00:00:00' and '2015-10-31 23:59:59'
group by Datepart(day,dateAdd(hour,0,ObservanceTime))