안녕하세요
생 초보 입니다.
일하는 중에 쓸일이 있어서 덜컥 이런 쿼리를 받았습니다.
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))