आप एक ही क्वेरी में दो अलग-अलग कॉलम काउंट करने के लिए CASE स्टेटमेंट का उपयोग कर सकते हैं। कॉन्सेप्ट समझने के लिए, आइए पहले एक टेबल बनाते हैं। टेबल बनाने की क्वेरी निम्नलिखित है:
mysql> create table CountDifferentDemo
-> (
-> ProductId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ProductName VARCHAR(20),
-> ProductColor VARCHAR(20),
-> ProductDescription VARCHAR(20)
-> ); Query OK, 0 rows affected (1.06 sec)
INSERT कमांड का उपयोग करके टेबल में कुछ रिकॉर्ड डालें।
क्वेरी निम्नलिखित है:
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-1','Red','Used'); Query OK, 1 row affected (0.46 sec)
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-1','Blue','Used'); Query OK, 1 row affected (0.17 sec)
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-2','Green','New'); Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-2','Blue','New'); Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-3','Green','New'); Query OK, 1 row affected (0.21 sec)
mysql> INSERT INTO CountDifferentDemo(ProductName,ProductColor,ProductDescription) VALUES('Product-4','Blue','Used'); Query OK, 1 row affected (0.20 sec)
SELECT स्टेटमेंट का उपयोग करके टेबल से सभी रिकॉर्ड प्रदर्शित करें।
क्वेरी निम्नलिखित है:
mysql> SELECT * FROM CountDifferentDemo;
निम्नलिखित आउटपुट है:
+-----------+-------------+--------------+--------------------+ | ProductId | ProductName | ProductColor | ProductDescription | +-----------+-------------+--------------+--------------------+ | 1 | Product-1 | Red | Used | | 2 | Product-1 | Blue | Used | | 3 | Product-2 | Green | New | | 4 | Product-2 | Blue | New | | 5 | Product-3 | Green | New | | 6 | Product-4 | Blue | Used | +-----------+-------------+--------------+--------------------+ 6 rows in set (0.01 sec)
एक ही क्वेरी में दो अलग-अलग कॉलम काउंट करने की क्वेरी निम्नलिखित है यानी हम एक विशेष कलर "Red" और डिस्क्रिप्शन "New" की घटनाओं को गिन रहे हैं:
mysql> SELECT ProductName,
-> SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color,
-> SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Description
-> FROM CountDifferentDemo
-> GROUP BY ProductName;
निम्नलिखित आउटपुट है:
+-------------+-------+------------+ | ProductName | Color | Description| +-------------+-------+------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-------+------------+ 4 rows in set (0.12 sec)