我有这个代码,可以按天输出取消行程的数量:
select request_at, count(*) as cancelled
from trip
where status = 'cancelled_by_client'
or status = 'cancelled_by_driver'
group by request_at order by request_at
它可以工作,但是,当没有取消的行程时,它不会输出任何内容。
我希望它输出“数据”和0作为取消值。
如何更改我的代码来执行此操作?
通过使用
Union ALL
和 CTE 表,您可以实现您想要的,如下所示:
;WITH query AS
(
select request_at, count(*) as cancelled
from trip
where status = 'cancelled_by_client'
or status = 'cancelled_by_driver'
group by request_at order by request_at
)
Select * from query
UNION ALL
Select 'data' as request_at, 0 as cancelled
where (Select count(*) from query) = 0 --if no rows in the query then attach this default values