Try this :
select
CASE
WHEN click_hour < '09' THEN '23 - 8'
WHEN click_hour < '12' THEN ' 8 - 11'
WHEN click_hour < '18' THEN '12 - 17'
WHEN click_hour < '23' THEN '18 - 22'
ELSE '23 - 8'
END AS time,
COUNT(*) AS quantity
from
(
SELECT
click_history_year||'-'||click_history_month||'-'||click_history_day||' '||click_history_hour as click_time,
substr(click_history_hour,1,2) as click_hour
FROM click_history
) as click_history2
WHERE datetime('now','-1 day') <= click_time
group by time
;
Note that this would be even cleaner if you just used a single column to store the timestamp (which I artificially created as click_time
). You would also eliminate the 4 columns you have now. To get the hour from the timestamp, use strftime(click_time, '%H')
.
Also, I adjusted the time ranges and comparisons, because some seemed wrong. Perhaps I just misunderstand your requirement.
And note that you could move the WHERE
clause up into the sub-query (and eliminate click_time
), but it depends upon how are going to use the code. It would be like this:
select
CASE
WHEN click_hour < '09' THEN '23 - 8'
WHEN click_hour < '12' THEN ' 8 - 11'
WHEN click_hour < '18' THEN '12 - 17'
WHEN click_hour < '23' THEN '18 - 22'
ELSE '23 - 8'
END AS time,
COUNT(*) AS quantity
from
(
SELECT
substr(click_history_hour,1,2) as click_hour
FROM click_history
WHERE datetime('now','-1 day') <= click_history_year||'-'||click_history_month||'-'||click_history_day||' '||click_history_hour
) as click_history2
group by time
;
Here is an SQLfiddle to check the syntax: http://sqlfiddle.com/#!7/992ca/2