Search code examples
sqlpostgresqlmetabase

SQL query how to divide two selects that return multiple columns


I have the following table :

city state numOrder date deadlineDate
NY NY 111 2022/11/05 2022/11/06
LA CA 222 2022/11/01 2022/10/01
SD CA 333 2022/05/05 2022/11/06
LA CA 444 2022/11/01 2022/05/01

I need to calculate the number of orders placed before the deadline divided by the number of orders placed by each state and city:

(SELECT state, city ,count(*) 
FROM orders
WHERE date <= deadlineDate
group by state, city) /
(SELECT state, city ,count(*) 
FROM orders
group by state, city)

I tried:

SELECT (
         SELECT state, city ,count(*) 
         FROM orders 
         WHERE serviceDate <= limitDate 
         group by state, city
       )/
       (
         SELECT state, city ,count(*) 
         FROM orders 
         group by state, city
       )
FROM orders

But the I got ERROR:

Subquery must return only one column


Solution

  • Try the following:

    SELECT state, city, 
           COUNT(*) FILTER (WHERE date <= deadlineDate)*1.0 / COUNT(*) AS result
    FROM orders
    GROUP BY state, city
    

    See a demo.