在日期查询中包含where子句

xt0899hw  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(268)

我遵循guido关于数据库中可能不存在给定日期的日期查询的优秀解决方案https://stackoverflow.com/a/36378448/6591500.
我已经把解决方案按原样处理了,没有任何问题。我现在需要扩展它来包含where子句。我有一个“日期”列和一个“结果”列,我需要在“结果”列中计算每一天的“通过”次数。
我的sql是这样的:

SELECT report_date, COUNT(*)-1 AS the_tally FROM (
SELECT date(report_date) as report_date FROM data as t1
WHERE 'spf_result' = 'pass'
UNION ALL 
    SELECT curdate() - interval a day AS report_date FROM (
        select 1 as a union select 2 union select 3 union
        select 4 union select 5 union select 6 union select 7 union
        select 8 union select 9 union select 10 union select 11 union
        select 12 union select 13 union select 14 
    ) as t2 
) as t3 GROUP BY report_date ORDER BY report_date DESC LIMIT 14

我期待的结果是:

report_date   The_tally
2020-06-11       4
2020-06-10       4
2020-06-09       6
2020-06-08       4

我得到的结果是:

report_date   The_tally
2020-06-11       0
2020-06-10       0
2020-06-09       0
2020-06-08       0

示例数据为:

report_date   spf_result
2020-06-11       pass
2020-06-11       pass
2020-06-11       pass
2020-06-11       pass
2020-06-10       pass
2020-06-10       pass
2020-06-10       pass
2020-06-10       pass
2020-06-09       pass
etc...

为什么我得到零?

vsnjm48y

vsnjm48y1#

你在比较两个字符串。
所以你必须用反勾
阅读mysql中何时使用单引号、双引号和反引号

SELECT report_date, COUNT(*)-1 AS the_tally FROM (
SELECT date(report_date) as report_date FROM data as t1
WHERE `spf_result` = 'pass'
UNION ALL 
    SELECT curdate() - interval a day AS report_date FROM (
        select 1 as a union select 2 union select 3 union
        select 4 union select 5 union select 6 union select 7 union
        select 8 union select 9 union select 10 union select 11 union
        select 12 union select 13 union select 14 
    ) as t2 
) as t3 GROUP BY report_date ORDER BY report_date DESC LIMIT 14
qlckcl4x

qlckcl4x2#

在查询中,第一部分不返回任何行,结果如下:

SELECT date(report_date) as report_date FROM data as t1
WHERE 'spf_result' = 'pass'

是空的,因为 'spf_result' = 'pass' 从来都不是真的。
p、 我认为你的意思是: WHERE spf_result = 'pass'

fwzugrvs

fwzugrvs3#

在您的查询中,其中“spf\u result”=“pass”更改为“spf\u result”=“pass”spf\u result是您的列,您的查询比较两个字符串,两个字符串都不同,因此“计数”中的计数显示为0,因为条件(“spf\u result”=“pass”)返回false
我试过摆弄你的例子数据
ddl地址:-

CREATE TABLE Table1
    (rdate date,
    status varchar(20)
    );

INSERT INTO Table1
(rdate,status)
VALUES ('2020-06-11','Passed'),('2020-06-11','Passed'),('2020-06-11','Passed'),('2020-06-11','Passed'),('2020-06-10','Passed'),('2020-06-10','Passed'),('2020-06-09','Passed'),('2020-06-10','Passed')
;

查询:-

select rdate,count(*)AS tally from table1 group by rdate order by rdate desc

输出:-

相关问题