SQL से Fee Summary Query
एक fee report
Fee summary एक मुख्य school-management report है: हर student ने कितना paid किया, कितना due है, और कुल collection। यह SUM और CASE (conditional aggregation) और student names को JOIN से बनती है — एक बहुत व्यावहारिक query।
Tables
students(id, name) fees(id, student_id, amount, status, paid_date) -- status 'paid' या 'due' है
प्रति fee item एक row, status और date के साथ store करना हमें status से total करने, dues list करने, और महीने से group करने देता है — सब सरल queries से।
प्रति student paid और due
SELECT s.name,
SUM(CASE WHEN f.status = 'paid' THEN f.amount ELSE 0 END) AS paid,
SUM(CASE WHEN f.status = 'due' THEN f.amount ELSE 0 END) AS due
FROM students s
JOIN fees f ON f.student_id = s.id
GROUP BY s.id, s.name;
दो CASE-SUMs amount को paid और due columns में बाँटते हैं, प्रति student grouped।
सिर्फ़ dues वाले students
SELECT s.name,
SUM(CASE WHEN f.status = 'due' THEN f.amount ELSE 0 END) AS due
FROM students s
JOIN fees f ON f.student_id = s.id
GROUP BY s.id, s.name
HAVING due > 0;
HAVING due > 0 जोड़ना सिर्फ़ उन students को रखता है जो अब भी पैसे बकाया हैं — बिल्कुल वो list जो office को fee reminders को चाहिए।
कुल collection
SELECT SUM(amount) AS total_collected FROM fees WHERE status = 'paid';
School-भर के आँकड़े को, बस सारे paid amounts जोड़िए। यह असल में collect किया कुल पैसा है।
महीने से collection
SELECT DATE_FORMAT(paid_date, '%Y-%m') AS month,
SUM(amount) AS collected
FROM fees
WHERE status = 'paid'
GROUP BY DATE_FORMAT(paid_date, '%Y-%m')
ORDER BY month;
Payment date के year-month से group करना monthly collection report देता है — साल भर cash flow track करने को उपयोगी।
आम गलतियाँ
- Paid/due को एक total store करना। लचीली reports को status वाली per-item rows रखिए।
- Due filter को WHERE इस्तेमाल करना। Due total एक aggregate है — HAVING इस्तेमाल कीजिए।
- CASE में ELSE 0 भूलना। इसके बिना, SUM NULLs अजीब ढंग से शामिल कर सकता है।
- Name और id से group न करना। सुरक्षित रहने को student key से group कीजिए।
सारांश
- प्रति item एक fee row status और date के साथ store कीजिए।
- प्रति student paid और due बाँटने को SUM(CASE ...) इस्तेमाल कीजिए।
- HAVING due > 0 अब भी बकाया students list करता है।
- कुल collection को paid amounts SUM कीजिए।
- Monthly collection report को महीने से GROUP BY कीजिए।
आगे, conditional totals सीखिए pivot table में, या पूरा school database बनाइए।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
MySQL में fee summary query कैसे बनाऊँ?
Paid और due amounts अलग-अलग कैसे निकालूँ?
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid और वही 'due' के साथ। हर SUM सिर्फ़ उस status से मेल खाते amounts जोड़ता है।अब भी fees बकाया वाले students कैसे ढूँढूँ?
HAVING SUM(CASE WHEN status = 'due' THEN amount ELSE 0 END) > 0। यह सिर्फ़ उन students को रखता है जिनकी due amount शून्य से ज़्यादा है।कुल fee collection कैसे पाऊँ?
SELECT SUM(amount) FROM fees WHERE status = 'paid';। Monthly report को, payment date के महीने से GROUP BY कीजिए।