GROUP BY MAX() के साथ डुप्लिकेट समूहों का अधिकतम मान
जब किसी कॉलम में डुप्लिकेट मान हों (जैसे उत्पाद नाम) और आपको प्रत्येक अद्वितीय मान के लिए अधिकतम संबंधित मान (जैसे मूल्य) चाहिए, तो GROUP BY के साथ MAX() का उपयोग करें।
टेबल और डेटा
mysql> CREATE TABLE DemoTable(
ProductName VARCHAR(100),
ProductPrice INT
);
Query OK, 0 rows affected (0.68 sec)
mysql> INSERT INTO DemoTable VALUES('Product-1',56);
Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO DemoTable VALUES('Product-2',78);
Query OK, 1 row affected (0.23 sec)
mysql> INSERT INTO DemoTable VALUES('Product-1',88);
Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO DemoTable VALUES('Product-2',86);
Query OK, 1 row affected (0.17 sec)
mysql> INSERT INTO DemoTable VALUES('Product-1',45);
Query OK, 1 row affected (0.18 sec)
mysql> INSERT INTO DemoTable VALUES('Product-3',90);
Query OK, 1 row affected (0.16 sec)
mysql> INSERT INTO DemoTable VALUES('Product-2',102);
Query OK, 1 row affected (0.22 sec)
mysql> INSERT INTO DemoTable VALUES('Product-3',59);
Query OK, 1 row affected (0.13 sec)
सभी रिकॉर्ड
mysql> SELECT * FROM DemoTable;
+-------------+--------------+ | ProductName | ProductPrice | +-------------+--------------+ | Product-1 | 56 | | Product-2 | 78 | | Product-1 | 88 | | Product-2 | 86 | | Product-1 | 45 | | Product-3 | 90 | | Product-2 | 102 | | Product-3 | 59 | +-------------+--------------+ 8 rows in set (0.00 sec)
प्रत्येक उत्पाद के लिए अधिकतम मूल्य
mysql> SELECT ProductName, MAX(ProductPrice) FROM DemoTable GROUP BY ProductName;
परिणाम:
+-------------+-------------------+ | ProductName | MAX(ProductPrice) | +-------------+-------------------+ | Product-1 | 88 | | Product-2 | 102 | | Product-3 | 90 | +-------------+-------------------+ 3 rows in set (0.00 sec)
व्याख्या: Product-1 के मूल्य 56, 88, 45 → अधिकतम 88। Product-2: 78, 86, 102 → अधिकतम 102। Product-3: 90, 59 → अधिकतम 90। GROUP BY प्रत्येक अद्वितीय उत्पाद के लिए एक पंक्ति बनाता है।