Ravindra BagaleCourses & study guides Track your progress

13. HAVING: Aggregate नंतर groups filter करा

13.2 HAVING SUM(amount) ने target पेक्षा मोठे groups ठेवा

का (Why). Regional head ला फक्त ज्या महिन्यांत branch ने target पार केलं ते महिने बघायचे आहेत, सगळे महिने नाहीत.

काय (What). HAVING SUM(amount) > आकडा फक्त ज्या groups चा total त्या आकड्यापेक्षा जास्त आहे ते ठेवतं. Currencies वेगळ्या ठेवा: भारतीय branches ची तुलना rupee target शी आणि London branch ची तुलना pound target शी करा.

कसं (How). Mumbai आणि Pune चे rows branch आणि महिन्यानुसार group करा, आणि मग फक्त 1,00,000 rupees पेक्षा जास्तचे groups ठेवा.

पायऱ्या

  1. पहिलं उदाहरण run करा आणि कुठल्या branch च्या कुठल्या महिन्यांनी 1,00,000 rupees पार केले ते वाचा.
  2. London साठी 5,000 pounds target ने दुसरं उदाहरण run करा.
  3. प्रत्येक query फक्त एकाच currency कडे बघते हे लक्षात घ्या.
  4. Target चा आकडा बदला आणि जास्त किंवा कमी groups बघायला परत run करा.

उदाहरणे

उदाहरण 1 · dataset: northstar_bank

SELECT branch_id,
       strftime('%Y-%m', posted_at) AS month,
       SUM(amount)                  AS total_inr
FROM transactions
WHERE branch_id IN (3, 4)
GROUP BY branch_id, month
HAVING SUM(amount) > 100000
ORDER BY branch_id, month;

Output

branch_idmonthtotal_inr
32026-08192000.0
32026-09276000.0
32026-10657000.0
42026-09166000.0

Meaning. फक्त 1,00,000 rupees पेक्षा जास्त total असलेले branch चे महिने उरतात. Pune चे August आणि October बाहेर राहतात, कारण त्यांचे totals त्या target पेक्षा कमी आहेत.

उदाहरण 2 · dataset: northstar_bank

SELECT strftime('%Y-%m', posted_at) AS month,
       SUM(amount)                  AS total_gbp
FROM transactions
WHERE branch_id = 1
GROUP BY month
HAVING SUM(amount) > 5000
ORDER BY month;

Output

monthtotal_gbp
2026-107950.0

Meaning. London साठी August आणि September 5,000 pounds च्या खाली राहतात. फक्त October 7,950 pounds सह target पार करतो.

Ravindra Bagale's Tip

SQLite lets you write HAVING total_inr > 100000 with the alias, but many other databases do not. Writing the full SUM(amount) works everywhere.