简体   繁体   English

如何每天计算相同的日期值

[英]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. 我想通过连接同一张表per day获取count Date(MYdatetime)类型值。

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 : 使用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: 在MySQL中,我将简单地执行以下操作:

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: 如果需要特定时间范围的数据,请使用where子句:

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). 您想要对给定时间范围内的所有日期进行计数,包括不在表中的那些日期(因此计数为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. 我认为从当前年份开始的10年半径范围会很好。 So fill it with every date between 2008-01-01 and 2028-12-31. 因此,请填写2008年1月1日至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. 可能有一种聪明的方法可以使用过程或类似方法在一个查询中生成所有行,但是我不知道它是什么,所以我个人只是创建一个简单的脚本(如PHP)来生成这些行。

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: 一旦all_dates表具有您需要的所有日期值行,您就可以执行查询以获取每个日期(包括缺失日期)的计数,例如:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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