2013-01-09 167 views
0

我想顯示col1重複的表的所有行。SELECT Col1,Col2,Col3 FROM Table WHERE Column1 has duplicates

+------+------+------+ 
| col1 | col2 | col3 | 
+------+------+------+ 
| 1 | 0 | 0 | 
| 1 | 1 | 1 | 
| 2 | 0 | 0 | 
| 3 | 0 | 0 | 
| 3 | 1 | 1 | 
| 4 | 0 | 0 | 
+------+------+------+ 

結果應該是:

+------+------+------+ 
| col1 | col2 | col3 | 
+------+------+------+ 
| 1 | 0 | 0 | 
| 1 | 1 | 1 | 
| 3 | 0 | 0 | 
| 3 | 1 | 1 | 
+------+------+------+ 

我已經試過,沒有運氣的一些疑問,所以在這裏我要求你的幫助。

回答

2

如果表的名稱T5然後使用這個:

SELECT COL1, COL2, COL3 
FROM T5 
WHERE COL1 IN 
(
    SELECT COL1 
    FROM T5 
    GROUP BY COL1 
    HAVING COUNT(COL1)>=2 
) 

我檢查了,上面不應該使用任何非標準的SQL。我假設其他人是這樣。

+1

這是什麼?:*「這不應該使用任何非標準的SQL」。*所有其他提供的答案也是標準SQL。 –

+0

是的,這是有道理的;我正在編輯提到這個的答案。 –

2
select col1, col2, col3 
from <yourTable> t1 
where exists 
    (select null 
    from <yourTable> t2 
    where t2.col1 = t1.col1 
    group by t2.col1 
    having count(*) > 1) 

sqlFiddle

3
select t.col1, t.col2, t.col3 
from mytable t join (select col1 
        from mytable 
        group by col1 
        having count(*) > 1) t2 
    on t.col1 = t2.col1 
6

根據您的SQL Server版本,你可以使用:

select col1, col2, col3 
from 
(
    select col1, col2, col3, 
    count(col1) over(partition by col1) cnt 
    from yourtable 
) src 
where cnt > 1 

SQL Fiddle with Demo

3

讓我再添加一個變體解決方案。如果你有一個pk列具有UNIQUEPRIMARY KEY約束,你可以使用:

select col1, col2, col3 
from <yourTable> t1 
where exists 
    (select * 
    from <yourTable> t2 
    where t2.col1 = t1.col1 
    and t2.pk <> t1.pk 
) ; 
1

猜猜我是太晚了..但如何對左連接...

SQLFIDDLE DEMO

查詢:

SELECT DISTINCT x.col1, x.col2, x.col3 
FROM ab y 
LEFT JOIN 
ab x 
ON y.col1=x.col1 and (y.col2<> x.col2 
        OR x.col3<>y.col3) 
where not (x.col3 is null) 
and not (x.col2 is null) 
; 

結果:

COL1 COL2 COL3 
1  0 0 
1  1 1 
3  0 0 
3  1 1 
+0

這不正是想要的:[SQL-Fiddle-2](http://sqlfiddle.com/#!3/a2b7d/1) –

+0

OP說結果應該是... – bonCodigo

+0

你檢查了我的小提琴(使用不同的數據,但你的代碼)?它不顯示2行'col1 = 1' –

相關問題