简体   繁体   中英

How to count the same date values per day

I'm completly begginer but and don't even know what type this query is.

BTW. I want to get count Date(MYdatetime) type values per day by join the same table.

Is there any question comparing this query?

I have query like that:

select 
    date_format(
        adddate('2011-1-1', @num:=@num+1), 
        '%Y-%m-%d'
    ) date
from 
    any_table,    
    (select @num:=-1) num
limit 
    365

Use GROUP BY :

SELECT 
    year(theDate), 
    month(theDate), 
    day(theDate), 
    count(*) 
FROM 
   test_table 
GROUP BY 
    year(theDate), 
    month(theDate), 
    day(theDate)

In MySQL, I would simply do:

select date(t.datecol), count(*)
from any_table t
group by date(t.datecol);

If you want data for a particular time span, use a where clause:

select date(t.datecol), count(*)
from any_table t
where t.datecol >= '2011-01-01' and t.datecol < '2012-01-01'
group by date(t.datecol);

You are wanting a count of all dates in a given time frame, including those dates that are not in the table (and thus would have a count of 0). This is a bit of a headache but not unprecedented. You basically need to create a utility table that is just every date you could possibly want and then do an outer join against that table. So create a simple table like:

CREATE TABLE `all_dates` (
  `the_date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And populate it with all dates you think you could potentially need. I think a 10 year radius from the current year would be good. So fill it with every date between 2008-01-01 and 2028-12-31.

INSERT INTO all_dates
(the_date) VALUES
('2008-01-01'),
('2008-01-02'),
('2008-01-03')

There is probably a clever way to generate all rows in one query using a procedure or somesuch, but I don't know what it would be, so I would personally just create a simple script (like in PHP) to generate those rows.

Once the all_dates table has all the date value rows for your needs, you can then do a query to get the count of each date (including missing dates) like:

SELECT DATE(all_dates.the_date), COUNT(any_table.datecol)
FROM any_table
RIGHT JOIN all_dates ON DATE(any_table.datecol) = all_dates.the_date
GROUP BY all_dates.the_date
HAVING all_dates.the_date BETWEEN '2011-01-01' AND '2012-01-01'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM