Skip to content
Worked Examples · Example 1.6

Q.Using the SALE table of the CARSHOWROOM database along with GROUP BY and the HAVING clause:

(a) Display the number of cars purchased by each customer from the SALE table.
(b) Display the customer Id and number of cars purchased, only if the customer purchased more than 1 car.
(c) Display the number of people in each category of payment mode from the SALE table.
(d) Display the PaymentMode and the number of payments made using that mode, only for modes used more than once.
West Bengal WbchseTextbookSubjective· 4mImportance★★★★★
28% · 11/40 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 →

GROUP BY collapses the 6-row SALE table into per-customer / per-payment-mode groups; HAVING then filters which GROUPS survive (unlike WHERE, which filters rows before grouping).

This is a code/query task. All four parts work on the same SALE table:

InvoiceNoCarIdCustIdSaleDatePaymentModeEmpIDSalePrice
I00001D001C00012019-01-24Credit CardE004613247.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) Grouping by CustID and counting rows per group gives one row per customer:

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

C0001 appears in rows I00001 and I00004 → 2 cars; C0002 in I00002 and I00006 → 2 cars; C0003 and C0004 each appear once.

(b) Adding HAVING COUNT(*)>1 keeps only the groups whose count exceeds 1 — C0001 and C0002:

SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING COUNT(*)>1;
Watch out

You cannot write this filter as WHERE COUNT(*)>1 — WHERE runs before grouping and cannot see an aggregate's result. The aggregate condition must go in HAVING, which runs after the groups are formed.

(c) The same idea, grouped by PaymentMode instead, with ORDER BY to sort the output alphabetically:

SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY PaymentMode ORDER BY 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.