日期:2014-05-17  浏览次数:21196 次

问个case when符合条件为空也显示一列的问题
例如:
SQL code

select case when a = '1' then 'a1' 
            when a = '2' then 'a2' 
            else  'aa' end ,count(*)
from table
group by case when a = '1' then 'a1' 
              when a = '2' then 'a2' 
              else  'aa' end



这样要是a='1'这个条件没有数据符合的话,根本不会显示'a1'行,有什么办法解决吗?

------解决方案--------------------
实测成功:


------解决方案--------------------
你这个查询量会非常大的。我仅用了一天的数据进行查询都要写N多代码。

--将时间值进行转化,不足5的,补齐为5
select ceil(to_char(sysdate,'mi')/5)*5 from dual

--首先日期字段每隔5分钟进行格式化,因为你没给表结构,我就直接用我自己的表了。
select to_date(to_char(acqdate, 'yyyy-mm-dd hh24') || ':' ||
decode(ceil(to_char(acqdate, 'mi') / 5) * 5,
60,
0,
ceil(to_char(acqdate, 'mi') / 5) * 5) || ':00',
'yyyy-mm-dd hh24:mi:ss') as recordTime,
count(1) as counted
from hi_dataacquisition
 group by to_date(to_char(acqdate, 'yyyy-mm-dd hh24') || ':' ||
decode(ceil(to_char(acqdate, 'mi') / 5) * 5,
60,
0,
ceil(to_char(acqdate, 'mi') / 5) * 5) || ':00',
'yyyy-mm-dd hh24:mi:ss')
--结果,这个是我表里的值
4 2011-11-29 11:00:00 2
5 2011-11-29 11:30:00 1
6 2011-11-29 14:45:00 1
7 2011-11-29 15:15:00 1

--延用上面的思路,先伪造每隔5分钟的记录,以一天为例
SELECT to_date('2011-11-29 ' || to_char(ceil((ROWNUM) * 5 / 60) - 1) || ':' ||
to_char(mod((ROWNUM - 1) * 5, 60)) || ':00',
'yyyy-mm-dd hh24:mi:ss') as service_date
FROM dual
CONNECT BY ROWNUM <= 288


--复杂的查询
select service_date,nvl(counted,0) from 
(SELECT to_date('2011-11-29 ' || to_char(ceil((ROWNUM) * 5 / 60) - 1) || ':' ||
to_char(mod((ROWNUM - 1) * 5, 60)) || ':00',
'yyyy-mm-dd hh24:mi:ss') as service_date
FROM dual
CONNECT BY ROWNUM <= 288) a
left join 
( select to_date(to_char(acqdate, 'yyyy-mm-dd hh24') || ':' ||
decode(ceil(to_char(acqdate, 'mi') / 5) * 5,
60,
0,
ceil(to_char(acqdate, 'mi') / 5) * 5) || ':00',
'yyyy-mm-dd hh24:mi:ss') as recordTime,
count(1) as counted
from hi_dataacquisition
 group by to_date(to_char(acqdate, 'yyyy-mm-dd hh24') || ':' ||
decode(ceil(to_char(acqdate, 'mi') / 5) * 5,
60,
0,
ceil(to_char(acqdate, 'mi') / 5) * 5) || ':00',
'yyyy-mm-dd hh24:mi:ss')
) b on a.service_date = b.recordTime 
order by a.service_date

--最终结果
132 2011-11-29 10:55:00 0
133 2011-11-29 11:00:00 2
134 2011-11-29 11:05:00 0
135 2011-11-29 11:10:00 0
136 2011-11-29 11:15:00 0
137 2011-11-29 11:20:00 0
138 2011-11-29 11:25:00 0
139 2011-11-29 11:30:00 1
140 2011-11-29 11:35:00 0
141 2011-11-29 11:40:00 0
142 2011-11-29 11:45:00 0
143 2011-11-29 11:50:00 0
144 2011-11-29 11:55:00 0
145 2011-11-29 12:00:00 0
146 2011-11-29 12:05:00 0
147 2011-11-29 12:10:00 0
148 2011-11-29 12:15:00 0
149 2011-11-29 12:20:00 0
150 2011-11-29 12:25:00 0
151 2011-11-29 12:30:00 0
152 2011-11-29 12:35:00 0
153 2011-11-29 12:40:00 0
154 2011-11-29 12:45:00 0
155 2011-11-29 12:50:00 0
156 2011-11-29 12:55:00 0
157 2011-11-29 13:00:00 0
158 2011-11-29 13:05:00 0
159 2011-11-29 13:10:00 0
160 2011-11-29 13:15:00 0
161 2011-