Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query Help (Advanced - for me!)

I have a question about a SQL query I am trying to write.

I need to query data from a database. The database has, amongst others, these 3 fields:

Account_ID #, Date_Created, Time_Created

I need to write a query that tells me how many accounts were opened per hour.

I have written said query, but there are times that there were 0 accounts created, so these "hours" are not populated in the results.

For example:

Volume Date__Hour
435 12-Aug-12 03
213 12-Aug-12 04
125 12-Aug-12 06

As seen in the example above, hour 5 did not have any accounts opened.

Is there a way that the result can populate the hour but and display 0 accounts opened for this hour? Example of how I want my results to look like:

Volume Date_Hour
435 12-Aug-12 03
213 12-Aug-12 04
0 12-Aug-12 05
125 12-Aug-12 06

Thanks!

Update: This is what I have so far

SELECT count(*) as num_apps, to_date(created_ts,'DD-Mon-RR') as app_date, to_char(created_ts,'HH24') as app_hour 
FROM accounts 
WHERE To_Date(created_ts,'DD-Mon-RR') >= To_Date('16-Aug-12','DD-Mon-RR') 
GROUP BY To_Date(created_ts,'DD-Mon-RR'), To_Char(created_ts,'HH24') 
ORDER BY app_date, app_hour
like image 214
EPRINGLES Avatar asked Sep 21 '26 20:09

EPRINGLES


1 Answers

To get the results you want, you will need to create a table (or use a query to generate a "temp" table) and then use a left join to your calculation query to get rows for every hour - even those with 0 volume.

For example, assume I have a table with app_date and app_hour fields. Also assume that this table has a row for every day/hour you wish to report on.

The query would be:

SELECT NVL(c.num_apps,0) as num_apps, t.app_date, t.app_hour
    FROM time_table t
    LEFT OUTER JOIN 
    (
    SELECT count(*) as num_apps, to_date(created_ts,'DD-Mon-RR') as app_date, to_char(created_ts,'HH24') as app_hour 
    FROM accounts 
    WHERE To_Date(created_ts,'DD-Mon-RR') >= To_Date('16-Aug-12','DD-Mon-RR') 
    GROUP BY To_Date(created_ts,'DD-Mon-RR'), To_Char(created_ts,'HH24') 
    ORDER BY app_date, app_hour
    ) c ON (t.app_date = c.app_date AND t.app_hour = c.app_hour)
like image 68
Mark Sherretta Avatar answered Sep 23 '26 09:09

Mark Sherretta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!