-4

mySQL dateTime range Query Issue

how get count of proceser in 2017 by same date like 2017-08-07


date         | name      
-----------------------
 2017-08-31   |  amr
-----------------------
 2017-08-05   |  ahmed
----------------- -----
     2018-08-08   | moh

how get 2017-01-01 BETWEEN 2017-12-31
------------------------
count         | date      
-----------------------
 2            |  2017
-----------------------
     1            | 2018
  SELECT  count(*)
    FROM item WHERE  
    date IN 
    ( SELECT  date 
     FROM item WHERE 
     (BETWEEN '2017-03-15' AND '2017-09-31')) 
Amr Essam
  • 35
  • 1
  • 5

3 Answers3

0

1, date is a reserved MySQL word. It would be best to name your column something else, but you can use it if you also specify the table name like table.date

2, there is no need for a sub-query. MySQL can do this in one query

SELECT count(`table.name`) as NUMBER, YEAR(`table.date`) as YR FROM item WHERE DATE(`table.date`) BETWEEN '2017-01-01' AND '2017-12-31'
Duane Lortie
  • 1,285
  • 1
  • 12
  • 16
0

BETWEEN is kind of a "ternary" operator, of the form x BETWEEN y AND z

You want:

`date` BETWEEN '2017-03-15' AND '2017-09-31'
Uueerdo
  • 15,723
  • 1
  • 16
  • 21
  • `date` BETWEEN '2017-03-15' AND '2017-09-31' and `date` BETWEEN '2018-03-15' AND '2018-09-31' – Amr Essam Aug 11 '17 at 20:40
  • You'd need "OR" not "and"; a single date cannot be in multiple non-overlapping date ranges any more than 2 can be in 1-3 AND 3-4. – Uueerdo Aug 11 '17 at 20:52
0

I couldn't find a duplicate for you, but I am sure there is one somewhere.

If you use GROUP BY and the DATE_FORMAT() function, you can COUNT() the occurrences in each group.

SELECT COUNT(*),DATE_FORMAT(`date`,'%Y') FROM `item` GROUP BY DATE_FORMAT(`date`,'%Y');

You can include a WHERE clause before GROUP BY if you need to omit certain ranges of time.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136