![](/img/trans.png)
[英]SQL - how to select all rows which have value1 in column but not value2 in same column?
[英]SQL QUERY: return the values1 which have the same value2 in other column, only if the values1 are different
我想查詢數據庫以獲取指向其他列中相同值的不同值。 例如:
表格1:
Letter : Number
a ---------------1
b ---------------1
b ---------------2
a ---------------1
a ---------------3
a ---------------3
c ---------------5
預期 output:
a ---------------1
b ---------------1
a ---------------1
不幸的是,我不使用支持 window 函數的 RDBMS。
你可以使用exists
:
select *
from mytable t
where exists (
select 1
from mytable t1
where t1.number = t.number and t1.letter != t.letter
)
在支持 window 功能的 RDBMS 上,您還可以執行 window count(distinct)
:
select t.number, t.letter
from (
select
t.number,
t.letter,
count(distinct t.letter) over(partition by t.letter) cnt
from mytable t
) t
where cnt > 1
MySQL 設置:
CREATE TABLE table1 ( Letter CHAR(1), number INT );
INSERT INTO table1 ( Letter, number )
SELECT 'a', 1 UNION ALL
SELECT 'b', 1 UNION ALL
SELECT 'b', 2 UNION ALL
SELECT 'a', 1 UNION ALL
SELECT 'a', 3 UNION ALL
SELECT 'a', 3 UNION ALL
SELECT 'c', 5
查詢:
SELECT *
FROM table1 t
WHERE EXISTS (
SELECT 1
FROM table1 x
WHERE x.number = t.number
GROUP BY number
HAVING COUNT( DISTINCT Letter ) > 1
)
Output :
信 | 號碼:----- | -----:一個| 1 b | 1個| 1
db<> 在這里擺弄
您可以使用COUNT
分析 function 在單個表掃描中執行此操作:
Oracle 設置
CREATE TABLE table1 ( Letter, "NUMBER" ) AS
SELECT 'a', 1 FROM DUAL UNION ALL
SELECT 'b', 1 FROM DUAL UNION ALL
SELECT 'b', 2 FROM DUAL UNION ALL
SELECT 'a', 1 FROM DUAL UNION ALL
SELECT 'a', 3 FROM DUAL UNION ALL
SELECT 'a', 3 FROM DUAL UNION ALL
SELECT 'c', 5 FROM DUAL
查詢:
SELECT Letter, "NUMBER"
FROM (
SELECT t.*,
COUNT( DISTINCT Letter ) OVER ( PARTITION BY "NUMBER" ) AS num_letters
FROM table1 t
)
WHERE num_letters > 1
Output :
信 | 號碼:----- | -----:一個| 1個| 1 b | 1
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.