snippetsqlMinor
How to write a query that counts rows by date?
Viewed 0 times
rowsquerywritedatethathowcounts
Problem
I have a database named
I have used the following query to get the data of single day,
It will give the count for the whole month. But instead of getting the count of the entire month as a whole, I want to get the output like following way, total count of each day in a month from a single SQL query.
emp1. There is a table named tx_feeder. I want to get the count of rows from that table. I have used the following query to get the data of single day,
select count (*) from tx_feeder
where datum between (select sysdate -31 from dual) and (select sysdate -1 from dual);
SQL> 3455890It will give the count for the whole month. But instead of getting the count of the entire month as a whole, I want to get the output like following way, total count of each day in a month from a single SQL query.
sysdate -31 = 11190
sysdate -30 = 13390
sysdate -29 = 65790
sysdate -28 = 44390
........
sysdate -1 = 14590Solution
That SQL dialect is from Oracle but this answer will be for MySQL.
If datum is DATE
If datum is DATETIME or TIMESTAMP
If you are looking for a grand total to be included, do
or
If datum is DATE
select count (*),datum date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by datum;If datum is DATETIME or TIMESTAMP
select count (*),DATE(datum) date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by DATE(datum);If you are looking for a grand total to be included, do
WITH ROLLUPselect count (*),datum date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by datum WITH ROLLUP;or
select count (*),DATE(datum) date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by DATE(datum) WITH ROLLUP;Code Snippets
select count (*),datum date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by datum;select count (*),DATE(datum) date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by DATE(datum);select count (*),datum date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by datum WITH ROLLUP;select count (*),DATE(datum) date from tx_feeder
where datum between (CURDATE() - INTERVAL 31 DAY)
and (CURDATE() - INTERVAL 1 DAY)
group by DATE(datum) WITH ROLLUP;Context
StackExchange Database Administrators Q#108697, answer score: 7
Revisions (0)
No revisions yet.