SQL 查询没有返回我想要的东西
SQL query not returning the things I want
我很困惑为什么我的查询没有return我想要的东西。有人可以帮我解决这个问题吗?
表格:
查询(CTE):
WITH cancel AS(
SELECT t.Request_at AS day, IFNULL(COUNT(t.Status),0) AS cancelled
FROM Trips t
LEFT JOIN Users u
ON t.Client_Id = u.Users_Id
WHERE (t.Status = "cancelled_by_driver" or t.Status = "cancelled_by_client")
AND t.Request_at BETWEEN "2013-10-01" AND "2013-10-03"
AND u.Banned = "No"
GROUP BY t.Request_at)
所以我在这里想要的是将我上面的 cte 设置为 return 未被禁止的用户取消的旅行次数或 driver 在 2013 年 10 月 1 日和 10 月 3 日之间,2013 年。我的查询是 return 为已取消的日期设置正确的号码,但对于没有取消的日期,它不是 returning “0”。我无法弄清楚为什么结果是这样的,因为我正在使用 IFNULL 并且已经使用了左连接。
where
子句会在您有机会将它们包含在结果集中之前驱逐没有取消驱动器的日期。
如果 table 中有所有可用日期(无论状态如何),您只需在聚合中移动条件即可:
select t.request_at,
sum(t.status in ('cancelled_by_driver', 'cancelled_by_client')) as cnt_cancelled
from trips t
inner join users u on u.user_id = t.client_id
where u.banned = 'No' and t.request_at between '2013-10-01' and '2013-10-03'
group by t.request_at
一种更通用的方法是使用日历 table 来处理日期,然后将 table 与 left join
相结合。如果您没有这样的 table,您可以使用递归查询即时生成它(在 MySQL 8.0 中可用):
with recursive cal as (
select '2013-10-01' as dt
union all
select dt + interval 1 day from cal where dt < '2013-10-03'
)
select c.dt, count(t.id) as cnt_cancelled
from cal c
left join trips t on t.request_at = c.dt and t.status in ('cancelled_by_driver', 'cancelled_by_client')
left join users u on u.user_id = t.client_id and u.banned = 'No'
group by c.dt
我很困惑为什么我的查询没有return我想要的东西。有人可以帮我解决这个问题吗?
表格:
查询(CTE):
WITH cancel AS(
SELECT t.Request_at AS day, IFNULL(COUNT(t.Status),0) AS cancelled
FROM Trips t
LEFT JOIN Users u
ON t.Client_Id = u.Users_Id
WHERE (t.Status = "cancelled_by_driver" or t.Status = "cancelled_by_client")
AND t.Request_at BETWEEN "2013-10-01" AND "2013-10-03"
AND u.Banned = "No"
GROUP BY t.Request_at)
所以我在这里想要的是将我上面的 cte 设置为 return 未被禁止的用户取消的旅行次数或 driver 在 2013 年 10 月 1 日和 10 月 3 日之间,2013 年。我的查询是 return 为已取消的日期设置正确的号码,但对于没有取消的日期,它不是 returning “0”。我无法弄清楚为什么结果是这样的,因为我正在使用 IFNULL 并且已经使用了左连接。
where
子句会在您有机会将它们包含在结果集中之前驱逐没有取消驱动器的日期。
如果 table 中有所有可用日期(无论状态如何),您只需在聚合中移动条件即可:
select t.request_at,
sum(t.status in ('cancelled_by_driver', 'cancelled_by_client')) as cnt_cancelled
from trips t
inner join users u on u.user_id = t.client_id
where u.banned = 'No' and t.request_at between '2013-10-01' and '2013-10-03'
group by t.request_at
一种更通用的方法是使用日历 table 来处理日期,然后将 table 与 left join
相结合。如果您没有这样的 table,您可以使用递归查询即时生成它(在 MySQL 8.0 中可用):
with recursive cal as (
select '2013-10-01' as dt
union all
select dt + interval 1 day from cal where dt < '2013-10-03'
)
select c.dt, count(t.id) as cnt_cancelled
from cal c
left join trips t on t.request_at = c.dt and t.status in ('cancelled_by_driver', 'cancelled_by_client')
left join users u on u.user_id = t.client_id and u.banned = 'No'
group by c.dt