I have an typical CUSTOMER/ORDERS set of tables and I want to display the total percentage of sales a particular customer is responsible for. I can get the total number of orders in the system like so:
SELECT COUNT(order_id) FROM orders
And I can get the the total number of orders made by the customer like so:
SELECT COUNT(order_id) FROM orders WHERE cust_id = 541
How can I combine these into a single query that returns the percentage of sales for a particular customer? Thanks!
One solution is to use a nested query-
To illustrate the flow, I have included more columns than you need to see in the final result set. Holding the count(order_id) in a temporary variable will be more efficient. I'm not used to postgres, I hope this works with minimal modification.
MySQL:
Edit
I guess it helps if I would have noticed the postgres tag. I thought it was a MySQL question.
PostgreSQL:
P.S. My PostgreSQL is rusty, so if the MySQL query works on PostgreSQL I'd like to know :)
Edit 2
I can't stress enough to be wary of the count(*) suggestion below. You generally want to avoid this with PostgreSQL.