SUM()
In this page:
SELECT SUM(column_name) FROM table_name [WHERE condition];
Totals Calculate करना
SUM() function matched rows में एक numeric column की सारी values जोड़ता है। यह total financial amounts या item quantities calculate करने के लिए ideal है, जैसे सभी orders से total revenue।
उदाहरण: Calculating Totals
CREATE TABLE orders (id INT, total INT);
INSERT INTO orders VALUES (1, 100), (2, 250);
SELECT SUM(total) AS total_revenue FROM orders;
Filters के साथ Summing
आप sum होने से पहले अपने addition को data के एक subset तक restrict कर सकते हैं। बस सिर्फ अपने filter से match करने वाली rows sum करने के लिए एक WHERE clause add करें, जैसे सिर्फ एक specific region से orders sum करना।
उदाहरण: Summing with Filters
CREATE TABLE orders (id INT, region TEXT, total INT);
INSERT INTO orders VALUES (1, 'North', 100), (2, 'South', 250);
SELECT SUM(total) AS north_total FROM orders WHERE region = 'North';
SUM() में NULL Values Handle करना
SUM() function automatically NULL values को zero मानने या calculation तोड़ने के बजाय ignore करता है। अगर एक row में NULL हो, इसे calculation को बिल्कुल affect किए बिना skip कर दिया जाता है।
उदाहरण: Handling NULL Values in SUM()
CREATE TABLE orders (id INT, total INT);
INSERT INTO orders VALUES (1, 100), (2, NULL), (3, 50);
SELECT SUM(total) AS total_ignoring_null FROM orders;
Expressions Sum करना
आप खुद SUM() function के अंदर arithmetic operations perform कर सकते हैं। final total sum होने से पहले हर row के लिए math calculate होता है, जैसे एक true order total पाने के लिए SUM(price * quantity)।
उदाहरण: Summing Expressions
CREATE TABLE order_items (id INT, price INT, quantity INT);
INSERT INTO order_items VALUES (1, 10, 3), (2, 20, 2);
SELECT SUM(price * quantity) AS order_total FROM order_items;
GROUP BY के साथ SUM()
आप category के हिसाब से एक total तोड़ने के लिए SUM() को एक GROUP BY clause के साथ combine कर सकते हैं। यह आपको अपने dataset में distinct categories के लिए totals calculate करने देता है, जैसे एक company-wide figure के बजाय प्रति product line revenue।
उदाहरण: SUM() with GROUP BY
CREATE TABLE orders (id INT, product_line TEXT, total INT);
INSERT INTO orders VALUES (1, 'Books', 50), (2, 'Toys', 30), (3, 'Books', 20);
SELECT product_line, SUM(total) AS line_total FROM orders GROUP BY product_line;
- यह उम्मीद करना कि
SUMno rows के लिए0return करेगा, जबकि यहNULLreturn करता है (COALESCE(SUM(x), 0)इस्तेमाल करें)। - numbers store करने वाला एक text column sum करना, जो strings convert करता है और गलत results दे सकता है।
- प्रति group एक total चाहते समय
GROUP BYभूल जाना।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: