Q.Consider the SALE table from the CARSHOWROOM database:
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Uses GROUP BY with COUNT(), and HAVING to filter the grouped results, run against the real SALE table (Table 9.11, CARSHOWROOM database) — not invented data.
SQL aggregate functions summarise a set of rows into one value. GROUP BY first collects rows into groups by a shared column value, then an aggregate like COUNT(*) runs once per group. HAVING filters those groups after aggregation — WHERE cannot do this, because WHERE filters individual rows before grouping.
The real SALE table (Table 9.11)
| InvoiceNo | CarId | CustId | SaleDate | PaymentMode | EmpID | SalePrice |
|---|---|---|---|---|---|---|
| I00001 | D001 | C0001 | 2019-01-24 | Credit Card | E004 | 613248.00 |
| I00002 | S001 | C0002 | 2018-12-12 | Online | E001 | 590321.00 |
| I00003 | S002 | C0004 | 2019-01-25 | Cheque | E010 | 604000.00 |
| I00004 | D002 | C0001 | 2018-10-15 | Bank Finance | E007 | 659982.00 |
| I00005 | E001 | C0003 | 2018-12-20 | Credit Card | E002 | 369310.00 |
| I00006 | S002 | C0002 | 2019-01-30 | Bank Finance | E007 | 620214.00 |
a) Number of cars purchased by each customer
SELECT CustID, COUNT(*) "Number of Cars"
FROM SALE
GROUP BY CustID;
Output
| CustID | Number of Cars |
|---|---|
| C0001 | 2 |
| C0002 | 2 |
| C0003 | 1 |
| C0004 | 1 |
4 rows in set (0.00 sec)
C0001 bought 2 cars (I00001, I00004), C0002 bought 2 (I00002, I00006), C0003 and C0004 bought 1 each.
b) Customers who purchased more than 1 car
SELECT CustID, COUNT(*)
FROM SALE
GROUP BY CustID
HAVING COUNT(*) > 1;
Output
| CustID | COUNT(*) |
|---|---|
| C0001 | 2 |
| C0002 | 2 |
2 rows in set (0.30 sec)
HAVING COUNT(*) > 1 keeps only the groups whose count exceeds 1 — C0003 and C0004 (count 1 each) are dropped.
c) Number of people in each category of payment mode
SELECT PaymentMode, COUNT(PaymentMode)
FROM SALE
GROUP BY Paymentmode
ORDER BY Paymentmode;
Output
| PaymentMode | Count(PaymentMode) |
|---|---| …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.