mysql查询,子查询返回多行

时间:2013-12-12 13:15:25

标签: mysql sql

我有两列日期t_dates_date。我正在计算s_datet_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”错误。

1 个答案:

答案 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;