簡體   English   中英

SQL - 組合兩個表時,在另一列中為另一列中的相同值查找具有不同值的所有行

[英]SQL - Finding all rows with a different values in a column for the same value in another column when combining two tables

我有兩個 MS Access Table 1Table 2 ,我對Col1Col2Col3中的值感興趣,其中Col2可能為空。 使用 SQL,我希望能夠組合兩個表,消除重復項並找到所有非空Col2值與Col3中的相同值不同的行。

Col2中沒有空值的兩個表的組合示例

+-----------+---------+---------+
|    Col1   |  Col2   |  Col3   |
+-----------+---------+---------+
| James     | bar     | 3       |
| Bob       | red     | 2       |
| Jess      | red     | 3       |
| Don       | foo     | 1       |
| James     | bar     | 1       |
| Mike      | red     | 3       |
| Paula     | foo     | 4       |
| Paula     | red     | 2       |
| Tom       | red     | 2       |
+-----------+---------+---------+

會給:

+-----------+---------+---------+
| James     | bar     | 3       |
| Jess      | red     | 3       |
| Mike      | red     | 3       |
| Don       | foo     | 1       |
| James     | bar     | 1       |
+-----------+---------+---------+

要合並表格並消除Col2不為空的重復項,我可以使用:

SELECT [Col1], [Col2], [Col3]
FROM [Table 1]
WHERE [Col2] <> ''
UNION ALL
SELECT [Col1], [Col2], [Col3]
FROM [Table 2]
WHERE [Col2] <> ''
GROUP BY [Col1], [Col2], [Col3]

使用上述語句的結果,我想知道應該使用哪個SELECT語句來完成我想要的。

你似乎想要exists

select distinct t.*
from table1 as t
where t.col2 is not null and
      exists (select 1
              from table1 as t2
              where t2.col3 = t.col3 and t2.col2 <> t.col2
             );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM