Skip to content
Worked Examples · Example 9.23

Q.Consider the SALE table from the CARSHOWROOM database:

a) Display the number of Cars purchased by each Customer from SALE table.
b) Display the Customer Id and number of cars purchased if the customer purchased more than 1 car from SALE table.
c) Display the number of people in each category of payment mode from the table SALE.
d) Display the PaymentMode and number of payments made using that mode more than once.
Tripura TbseTextbookSubjective· 4mImportance★★★★★
40% · 38/95 Questions
🔒 Locked · start free trial →

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)

InvoiceNoCarIdCustIdSaleDatePaymentModeEmpIDSalePrice
I00001D001C00012019-01-24Credit CardE004613248.00
I00002S001C00022018-12-12OnlineE001590321.00
I00003S002C00042019-01-25ChequeE010604000.00
I00004D002C00012018-10-15Bank FinanceE007659982.00
I00005E001C00032018-12-20Credit CardE002369310.00
I00006S002C00022019-01-30Bank FinanceE007620214.00

a) Number of cars purchased by each customer

SELECT CustID, COUNT(*) "Number of Cars"
FROM SALE
GROUP BY CustID;

Output

CustIDNumber of Cars
C00012
C00022
C00031
C00041

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

CustIDCOUNT(*)
C00012
C00022

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.