1

I've got two columns of dates, t_date and s_date. I'm counting the number of records occurring where s_date is either the same date as t_date or within an n day window after t_date occurs.

Here is the query. It returns multiple rows.

select count(id)
from customers
where s_date >= t_date
and s_date <= t_date + 1
group by t_date;

Is there any way to design a query that contains several sub queries that each return multiple rows? So that I can increment the time window? Something like:

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;

This query, however, returns a "Sub query returns more than 1 row" error.

1 Answer 1

7

You can use the CASE expression:

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Way better than the sub queries the OP asked for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.