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 ठेवा.
पायऱ्या
- पहिलं उदाहरण run करा आणि कुठल्या branch च्या कुठल्या महिन्यांनी 1,00,000 rupees पार केले ते वाचा.
- London साठी 5,000 pounds target ने दुसरं उदाहरण run करा.
- प्रत्येक query फक्त एकाच currency कडे बघते हे लक्षात घ्या.
- 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_id | month | total_inr |
|---|---|---|
| 3 | 2026-08 | 192000.0 |
| 3 | 2026-09 | 276000.0 |
| 3 | 2026-10 | 657000.0 |
| 4 | 2026-09 | 166000.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
| month | total_gbp |
|---|---|
| 2026-10 | 7950.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.
Ravindra Bagale's Tip – मराठी
SQLite मध्ये HAVING total_inr > 100000 असं alias वापरून लिहिता येतं, पण बऱ्याच इतर databases मध्ये नाही. पूर्ण SUM(amount) लिहिलं तर ते सगळीकडे चालतं.
Ravindra Bagale's Tip – हिंदी
SQLite में HAVING total_inr > 100000 जैसा alias लिख सकते हैं, पर कई दूसरे databases में नहीं। पूरा SUM(amount) लिखेंगे तो वह हर जगह चलेगा।