0

I have below mentioned sql query which gives me simple count as on that date or if i use where and and condition for date it gives me consolidated count between the date.

select count(*) from A where date(date_1) = '2017-06-01';

I want count for a range of date for separate count for each date.

select count(*) from A where date(date_1) >= '2017-06-01' and date(date_1)<='2017-06-30';

Desired output:

Date          Count

2017-06-01    25
2017-06-02    20
2017-06-03    15
-             -
-             -
2017-06-30    10
Vector JX
  • 179
  • 4
  • 23

3 Answers3

2

All you need is to use group by clause like:

SELECT date(date_1),Count(*) as [Count]
FROM A
WHERE date(date_1) >= '2017-06-01' and date(date_1)<='2017-06-30'
GROUP BY date(date_1)
Eray Balkanli
  • 7,752
  • 11
  • 48
  • 82
2

Something like the following might work:

SELECT DATE(date_1), COUNT(*)
FROM A
GROUP BY DATE(date_1)

COUNT, being an aggregate function, is often combined with the GROUP BY clause in order to get aggregate results per group (in this case, counts per date).

WHERE clauses can of course be added as desired, right before the GROUP BY clause.

ngj
  • 883
  • 7
  • 17
1

The following solution also reports days with no noted incidents. The example is devised for the month of February:

    SELECT (DATE'2018-01-31' + INTERVAL x.n DAY) dd
         , COALESCE(sqt.c, 0)                    incidents
      FROM (select 1 n union all select 2 n union all select 3 n union all select 4 n union all select 5 n union all select 6 n union all select 7 n union all select 8 n union all select 9 n union all select 10 n union all select 11 n union all select 12 n union all select 13 n union all select 14 n union all select 15 n union all select 16 n union all select 17 n union all select 18 n union all select 19 n union all select 20 n union all select 21 n union all select 22 n union all select 23 n union all select 24 n union all select 25 n union all select 26 n union all select 27 n union all select 28 n) x
 LEFT JOIN (
                SELECT date1    d
                     , count(*) c
                  FROM t
              GROUP BY date1
           ) sqt
        ON sqt.d = (DATE'2018-01-31' + INTERVAL x.n DAY)
         ; 

The standalone demo can be viewed here.

The sequence generator has been shamelessly adopted from this SO answer.

collapsar
  • 17,010
  • 4
  • 35
  • 61