GROUP BY
In this page:
SELECT column_name, aggregate_function(column)
FROM table_name
GROUP BY column_name;
Simple Grouping
GROUP BY clause shared column values के आधार पर matching data rows को साथ summary groups में collect करता है। यह आपके data को summarize करने के लिए aggregate functions के साथ इस्तेमाल होता है, कई rows को प्रति group एक row में condense करते हुए।
उदाहरण: Simple Grouping
CREATE TABLE orders (id INT, customer_id INT);
INSERT INTO orders VALUES (1, 1), (2, 1), (3, 2);
SELECT customer_id FROM orders GROUP BY customer_id;
COUNT() के साथ Grouping
आप GROUP BY को COUNT() के साथ pair करके यह count कर सकते हैं कि हर group में कितनी rows हैं। यह item statistics generate करने का सबसे common तरीका है, जैसे हर customer ने कितने orders place किए हैं।
उदाहरण: Grouping with COUNT()
CREATE TABLE orders (id INT, customer_id INT);
INSERT INTO orders VALUES (1, 1), (2, 1), (3, 2);
SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id;
SUM() के साथ Grouping
आप GROUP BY को SUM() के साथ pair करके हर group के लिए mathematical totals calculate कर सकते हैं। यह आपको एक number में lumped होने के बजाय category से broken down product sales या inventory totals calculate करने में मदद करता है।
उदाहरण: Grouping with SUM()
CREATE TABLE sales (id INT, category TEXT, amount INT);
INSERT INTO sales VALUES (1, 'Books', 50), (2, 'Toys', 30), (3, 'Books', 20);
SELECT category, SUM(amount) AS total_sales FROM sales GROUP BY category;
कई Columns पर Grouping
आप एक साथ एक से ज़्यादा column से rows group कर सकते हैं, जैसे region और product category दोनों से group करना। यह आपके query results में highly detailed sub-groups बनाता है, grouped columns के हर unique combination के लिए एक row।
उदाहरण: Grouping on Multiple Columns
CREATE TABLE sales (id INT, region TEXT, category TEXT, amount INT);
INSERT INTO sales VALUES (1, 'North', 'Books', 50), (2, 'North', 'Toys', 20), (3, 'South', 'Books', 30);
SELECT region, category, SUM(amount) AS total FROM sales GROUP BY region, category;
ORDER BY के साथ GROUP BY
GROUP BY द्वारा rows collapse करने के बाद आप ORDER BY इस्तेमाल करके अपना grouped summary data sort कर सकते हैं। यह आपको अपने groups को highest से lowest metrics तक rank करने देता है, जैसे पहले अपनी top-selling categories ढूँढना।
उदाहरण: GROUP BY with ORDER BY
CREATE TABLE sales (id INT, category TEXT, amount INT);
INSERT INTO sales VALUES (1, 'Books', 50), (2, 'Toys', 90), (3, 'Books', 20);
SELECT category, SUM(amount) AS total FROM sales GROUP BY category ORDER BY total DESC;
- एक non-grouped, non-aggregated column select करना, जो
ONLY_FULL_GROUP_BYके तहत error देता है। COUNT(*) > 1जैसे किसी aggregate को filter करने के लिएWHEREइस्तेमाल करना, जिसेHAVINGचाहिए।- गलत column से group करना, ताकि counts intended से अलग चीज़ describe करें।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: