我有两列日期t_date
和s_date
。我正在计算s_date
与t_date
的日期相同或在t_date
发生后的n天窗口内发生的记录数。
这是查询。它返回多行。
select count(id)
from customers
where s_date >= t_date
and s_date <= t_date + 1
group by t_date;
有没有办法设计一个包含多个sub queries
的查询,每个查询返回多行?这样我可以增加时间窗口?类似的东西:
select (
select count(id)
from customers
where s_date >= t_date
and s_date <= t_date + 1
group by t_date
) as c1,
(
select count(id)
from customers
where s_date >= t_date
and s_date <= t_date + 2
group by t_date
) as c2;
但是,此查询会返回“Sub query returns more than 1 row
”错误。
答案 0 :(得分:7)
您可以使用CASE
表达式:
SELECT
SUM(CASE WHEN s_date >= t_date AND s_date <= t_date + 1 THEN 1 ELSE 0 END) AS c1,
SUM(CASE WHEN s_date >= t_date AND s_date <= t_date + 2 THEN 1 ELSE 0 END) AS c2
...
FROM customers
GROUP BY t_date;