![](/img/trans.png)
[英]ORACLE SQL: select multiple rows basd on different values in one column for a same key value in another column
[英]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 1
和Table 2
,我對Col1
、 Col2
和Col3
中的值感興趣,其中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.