GROUP BY का उपयोग
GROUP BY rows को groups में split करता है ताकि हर group को अपना aggregate result मिले।
In this page:
Syntax
SELECT group_column, aggregate_function(column)
FROM table_name
GROUP BY group_column;
GROUP BY
हर selected column या तो GROUP BY में होना चाहिए या एक aggregate function के अंदर। आप कई columns और expressions से group कर सकते हैं।
Group order guaranteed नहीं है, इसलिए ORDER BY add करें।
PostgreSQL column position और alias से group करना allow करता है, हालाँकि names clearer हैं।
Note:
predictable result order के लिए GROUP BY के बाद ORDER BY add करें।
उदाहरण: GROUP BY
CREATE TABLE sales (id INTEGER PRIMARY KEY, item TEXT, region TEXT, qty INTEGER);
INSERT INTO sales VALUES (1,'pen','N',5),(2,'book','N',1),(3,'pen','S',10),(4,'book','S',3),(5,'lamp','N',2);
SELECT item, SUM(qty) AS total_qty, COUNT(*) AS orders FROM sales GROUP BY item ORDER BY item;
SELECT region, item, SUM(qty) AS total_qty FROM sales GROUP BY region, item ORDER BY region, item;
-- Output:
-- item | total_qty | orders
-- book | 4 | 2
-- lamp | 2 | 1
-- pen | 15 | 2
-- region | item | total_qty
-- N | book | 1
-- N | lamp | 2
-- N | pen | 5
-- S | book | 3
-- S | pen | 10
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- ऐसे columns select करना जो grouped या aggregated नहीं हैं
- sorted output की उम्मीद करना
- बहुत सारे columns से group करना
चैप्टर सारांश
- GROUP BY प्रति group एक row बनाता है
- Selected columns grouped या aggregated होने चाहिए
- कई columns finer groups देते हैं
- Order के लिए ORDER BY add करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: