简体   繁体   English

MySQL - 计算日期范围内的行出现次数,但将null转换为0,以便显示

[英]MySQL - count row occurrences in a date range, but convert null to 0 so it shows

This is my current query 这是我目前的查询

SELECT DAYNAME(date_created) AS Day, 
COUNT(*) AS my_count FROM sometable 
WHERE (@date_created >= '2010-10-20 21:02:38' OR @date_created IS NULL) 
AND (@date_created <= '2010-10-27 21:02:38' OR @date_created IS NULL) 
GROUP BY DAY(date_created)

It only returns data for that day if the count exists. 如果计数存在,它仅返回该日的数据。

I was mucking around with ifnull, but no luck 我和ifnull在一起,但没有运气

Im sure this is an easy one, but i can't figure it out! 我确定这是一个简单的,但我无法弄清楚!

Any help would be so appreciated 任何帮助都会非常感激

Use COALESCE : 使用COALESCE:

SELECT COALESCE(x,0) AS val FROM table; SELECT COALESCE(x,0)AS val FROM table;

if x is null, it will return 0 如果x为null,则返回0

MySQL lacks a way to generate a recordset in runtime (like generate_series in PostgreSQL ). MySQL缺乏在运行时生成记录集的方法(如PostgreSQL generate_series )。

The only way to do this query is to keep around a table of all possible dates (or, better, a smaller table you can cross-join with itself): 执行此查询的唯一方法是保留所有可能日期的表(或者,更好的是,您可以与自身交叉连接的较小表):

CREATE TABLE a (a INT PRIMARY KEY);

INSERT
INTO    a
VALUES
        (0),
        (1),
        …
        (99)

Then you can generate a list of all possible dates and left join your table with it: 然后,您可以生成所有可能日期的列表,并使用它连接您的表:

SLEECT  '2010-01-01' + INTERVAL 10000 * a1.a + 100 * a2.a + a3.a DAY AS dt,
        COUNT(date_created)
FROM    a a1
CROSS JOIN
        a a2
CROSS JOIN
        a a3
LEFT JOIN
        sometable
ON      date_created = '2010-01-01' + INTERVAL 10000 * a1.a + 100 * a2.a + a3.a DAY
WHERE   (a1.a, a2.a, a3.a) <= (0, 3, 65)
GROUP BY
        dt

This condition: 这个条件:

(a1.a, a2.a, a3.a) <= (0, 3, 65)

means "take 365 records". 意思是“拍摄365条记录”。

Welcome Doug! 欢迎道格! I ran a modified version of your SQL locally and I'm getting results even for those NULL dates. 我在本地运行了SQL的修改版本,即使是那些NULL日期我也得到了结果。 First things first - to real-time convert a null into some other value ("convert null to 0") you need to use the MySQL statement IF , if you know anything of Oracle, it's a lot like the DECODE command. 首先要做的是 - 要实时将null转换为其他值(“将null转换为0”),您需要使用MySQL语句IF ,如果您对Oracle有所了解,那就像DECODE命令一样。 A NULL value automatically evaluates to false, so you can simply write: NULL值自动计算为false,因此您只需编写:

SELECT IF(date_created,date_created,0) FROM sometable

Of course... 0 isn't anymore a date then NULL is. 当然...... 0不再是日期,那么NULL就是。 I found the DAYNAME function simply passes on NULL dates for you to deal with: 我发现DAYNAME函数只是传递NULL日期,你可以处理:

SELECT DAYNAME(date_created) day,COUNT(*) my_count 
FROM sometable
WHERE date_created IS NULL OR
 (date_created>='2010-10-20 21:02:38' AND date_created <= '2010-10-27 21:02:38')
GROUP BY DAY(date_created)

What I'm getting out of that (with an example data set) is 8 values of day : 7 days of the week + NULL (with a count). 什么我得到了那(带有示例数据集)是8个值day :7天周+空的(用计数)。 Which kinda makes sense... you can't convert an unknown date into a day of the week. 哪种方式有意义......您无法将未知日期转换为一周中的某一天。

It could have been your errant @ signs in your SQL, unless I'm misunderstanding your purpose. 它可能是你的SQL中的错误@符号,除非我误解你的目的。

UPDATE UPDATE

Based on your last comment, you need to take over processing in PHP. 根据您的上一条评论,您需要接管PHP中的处理。 Build the days array before hand, then add the MySQL data to your existing array so that all the days are there (and in order). 事先构建days数组,然后将MySQL数据添加到现有数组中,以便所有日期都存在(并按顺序)。

Source : day-counting in PHP 来源PHP中的日计算

//You may not even need "date_created IS NULL OR" in the where statement
$sql="SELECT DAYNAME(date_created) day,COUNT(*) my_count 
    FROM sometable
    WHERE date_created IS NULL OR
     (date_created>='2010-10-20 21:02:38' 
      AND date_created <= '2010-10-27 21:02:38')
    GROUP BY DAY(date_created)";
//We're assuming you've setup a MySQL connection in $conn
$result = @mysql_query($sql, $conn) or die(mysql_error());

//Starting data - Zero for every day
$days=array("Sunday"=>0,"Monday"=>0,"Tuesday"=>0,"Wednesday"=>0,
   "Thursday"=>0,"Friday"=>0,"Saturday"=>0);
while($row = mysql_fetch_array($result)) {
   $days[$row["day"]]+=$row["my_count"];
}
mysql_free_result($result);

//Preview the output
print_r($days);

The @ sign describes a user variable - are you pulling date_created from sometable? @符号描述了一个用户变量 - 你是否从某个表中提取date_created? If so, remove the @ sign from the variables. 如果是这样,请从变量中删除@符号。

Not sure why you would want to include date_created if it's null. 不确定为什么要包含date_created,如果它为null。 Maybe some sample rows and desired output would help in illustrating exactl what you're looking for. 也许一些示例行和所需的输出将有助于说明您正在寻找的内容。 Good luck! 祝好运! :) :)

使用@时保持一致

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

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