MySQL Aggregate Functions
In this page:
SELECT COUNT(*), SUM(column_name), AVG(column_name),
MIN(column_name), MAX(column_name)
FROM table_name;
Aggregate Functions क्या हैं?
एक aggregate function rows का एक set input की तरह लेता है और उन्हें एक single summary value में collapse कर देता है, जैसे एक total count, sum, या average, individual rows खुद return करने के बजाय।
उदाहरण: What are Aggregate Functions?
CREATE TABLE orders (id INT, total INT);
INSERT INTO orders VALUES (1, 50), (2, 30), (3, 70);
SELECT COUNT(*) AS order_count, SUM(total) AS total_sum FROM orders;
एक नज़र में COUNT, SUM, और AVG
COUNT बताता है कि कितनी rows match करती हैं, SUM एक numeric column की values जोड़ता है, और AVG उनका mean compute करता है -- ये तीन numeric या countable data summarize करने के लिए सबसे commonly इस्तेमाल होने वाले aggregate functions हैं।
उदाहरण: COUNT, SUM, and AVG at a Glance
CREATE TABLE orders (id INT, total INT);
INSERT INTO orders VALUES (1, 50), (2, 30), (3, 70);
SELECT COUNT(*) AS cnt, SUM(total) AS sum_total, AVG(total) AS avg_total FROM orders;
एक नज़र में MIN और MAX
MIN और MAX matching rows में किसी column में मिली सबसे छोटी और सबसे बड़ी values return करते हैं, जो हर row manually scan किए बिना सबसे सस्ता product या सबसे बड़ा order जैसी extremes ढूँढने के लिए उपयोगी है।
उदाहरण: MIN and MAX at a Glance
CREATE TABLE products (id INT, price INT);
INSERT INTO products VALUES (1, 20), (2, 5), (3, 100);
SELECT MIN(price) AS cheapest, MAX(price) AS priciest FROM products;
GROUP BY के साथ Aggregates
Aggregate functions अक्सर GROUP BY के साथ combine होते हैं, जो किसी column की value के आधार पर result को अलग buckets में split करता है, ताकि aggregate पूरी table पर एक साथ नहीं बल्कि हर group के लिए independently calculate हो।
उदाहरण: Aggregates with GROUP BY
CREATE TABLE orders (id INT, region TEXT, total INT);
INSERT INTO orders VALUES (1, 'North', 50), (2, 'South', 30), (3, 'North', 70);
SELECT region, SUM(total) AS region_total FROM orders GROUP BY region;
एक Aggregate Function कब इस्तेमाल करें
Aggregate functions सही tool हैं जब भी किसी query को कितने, कितना, या average क्या है जैसे summary question का जवाब देना हो, और वे अपनी computed aggregate value के आधार पर groups filter करने के लिए naturally HAVING के साथ pair होते हैं।
उदाहरण: When to Use an Aggregate Function
CREATE TABLE orders (id INT, region TEXT, total INT);
INSERT INTO orders VALUES (1, 'North', 50), (2, 'South', 30), (3, 'North', 70);
SELECT region, SUM(total) AS region_total
FROM orders
GROUP BY region
HAVING SUM(total) > 40;
- बिना
GROUP BYके एक plain column को एक aggregate के साथ mix करना, जैसेSELECT name, COUNT(*), जो strict mode में error देता है। - यह उम्मीद करना कि
COUNT(column)NULLvalues count करेगा, जबकि सिर्फCOUNT(*)हर row count करता है। WHEREमें एक aggregate function इस्तेमाल करना, जिसकी अनुमति नहीं है (HAVINGइस्तेमाल करें)।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: