Let's say I have a table representing sales with these attributes:
SELECT COUNT(*) AS n_cancelled FROM sales WHERE cancellor = "Joe"
SELECT COUNT(*) AS n_sales FROM sales
STATE in ("sold", "cancelled")
AND (vendor = "Joe" OR buyer = "Joe")
You can use conditional aggregation:
SELECT SUM(cancellor = 'Joe') as n_cancelled, SUM(state in ('sold', 'cancelled') AND 'Joe' IN (vendor, buyer)) AS n_sales FROM sales WHERE ( (cancellor = 'Joe') or (state in ('sold', 'cancelled') AND 'Joe' IN (vendor, buyer)) );
You can do the division in the query as well.
Note: This keeps the
WHERE clause, which is not strictly necessary. But reducing the number of rows before aggregating the data can improve performance.