3

I have a database named 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> 3455890

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.

     sysdate -31 = 11190  
     sysdate -30 = 13390  
     sysdate -29 = 65790  
     sysdate -28 = 44390   
     ........  
     sysdate -1 = 14590
1
  • Read about the GROUP BY operator.
    – mustaccio
    Commented Jul 31, 2015 at 18:29

1 Answer 1

7

That SQL dialect is from Oracle but this answer will be for MySQL.

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 ROLLUP

select 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;
1
  • Wouldn't it be better to use CURDATE() instead of NOW()? At least if datum is a DATE.
    – Andriy M
    Commented Jul 31, 2015 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.