2014-06-05 66 views
0

我有類似如下的select語句行:只選擇其中的列值出現不止一次

select * 
from A 
    inner join B on A.id_x = B.id_x 
    inner join C on B.id_y = C.id_y 
    inner join D on C.id_z = D.id_z 
where 
    A.date > '2014-01-01' 
    and A.id_y = 154 
    and D.id_t = 2 

我要的是做這樣的事情and count(A.id_x) > 1,僅返回原來的部分選擇A.id_x上的哪一個重複。

這可能嗎?

編輯:

我只是嘗試使用臨時表來解決這個問題,與我從T-SQL Insert into table without having to specify every column

Select * Into 
    #tmpBigTable 
    From [YourBigTable] 

了代碼,但我得到一個錯誤信息,因爲我的表具有相同的列名,A.id_x例如,B.id_x

「每個表格中的列名必須是唯一的。」

有沒有辦法強制這個問題,或者聲明任意的命名擴展?

回答

2
select * 
from A 
    inner join B on A.id_x = B.id_x 
    inner join C on B.id_y = C.id_y 
    inner join D on C.id_z = D.id_z 
where 
    A.date > '2014-01-01' 
    and A.id_y = 154 
    and D.id_t = 2 
    AND A.id_x IN 
    (
    SELECT A.id_x FROM A 
    GROUP BY A.id_x 
    HAVING count(A.id_x)>1); 
+0

謝謝。這似乎工作。我嘗試了它,並一直沒有得到任何結果(但沒有錯誤),並且認爲某些事情是錯誤的,直到我用'> 0'測試它,並且意識到沒有特定的一組子句。 – user38858

1

你可以用窗口函數做到這一點:

select * 
from (select *, count(*) over (partition by A.id_x) as cnt 
     from A inner join 
      B 
      on A.id_x = B.id_x inner join 
      C 
      on B.id_y = C.id_y inner join 
      D 
      on C.id_z = D.id_z 
     where A.date > '2014-01-01' and A.id_y = 154 and D.id_t = 2 
    ) abcd 
where cnt > 1; 
相關問題