简体   繁体   中英

SQL Query to show opposite values

I need help in this query. Suppose there is the following table

| Node_Name| Status |
+----------+-----------+
| Node_1   | a |
| Node_1   | b |
| Node_2   | c |
| Node_2   | a |
| Node_3   | b |
| Node_3   | c |

I need to get all the statuses that a node does not have.

For example output should be as follows:

 | Node_Name| Status |
 +----------+-----------+
 | Node_1   | c |
 | Node_2   | b |
 | Node_3   | a |

Any help would be great! thanks

First find all the possible combination of node_name and status

Then Left Outer join the above result with yourtable and filter only the non matching records to get the result

Try this

SELECT A.node_name, 
       B.status 
FROM   (SELECT DISTINCT node_name 
        FROM   yourtable) A 
       CROSS JOIN (SELECT DISTINCT status 
                   FROM   yourtable) B 
       LEFT OUTER JOIN yourtable C 
                    ON A.node_name = C.node_name 
                       AND C.status = B.status 
WHERE  C.status IS NULL 

This is a pretty tricky query because it the result is outside of the set of the table.

SELECT
    full_set.*
FROM
    (
        SELECT DISTINCT
            Node_Name,
            statuses.Status
        FROM
            table1
        CROSS JOIN(SELECT Status FROM table1)statuses
    ) full_set
LEFT JOIN table1 original_table 
  ON full_set.Node_Name = original_table.Node_Name AND full_set.Status = original_table.Status
WHERE
    original_table.Node_Name IS NULL
AND original_table.Status IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM