2016-09-18 36 views
0

下面的T-SQL顯示其下面的表中顯示的結果。我想以一種排除UserID爲1,95和161的行的方式編寫T-SQL。這些行只出現一次,我不想將它們包含在結果集中。我想要的是顯示用戶標識出現多次的行。任何幫助將不勝感激。非常感謝!消除記錄集中的非重複行

select top(100) UserID, PhotoLabel 
from dbo.Photos 
where left(PhotoLabel, 8) in ( 
           select distinct top(10) left(PhotoLabel, 8) as date 
           from dbo.Photos 
           order by left(PhotoLabel,8) desc 
          ) 
order by UserID asc, left(PhotoLabel,8); 


UserID   PhotoLabel 
======   ============== 
    1   20160702064633 
    2   20150915101504 
    2   20150915101307 
    2   20150915101152 
    95   20150726135443 
    159   20160330234026 
    159   20160330234018 
    161   20160223112742 

回答

2

只需將條件添加到where條款:

select top(100) UserID, PhotoLabel 
from dbo.Photos 
where left(PhotoLabel, 8) in (select distinct top(10) left(PhotoLabel, 8) as date 
           from dbo.Photos 
           order by left(PhotoLabel, 8) desc 
          ) and 
     UserId not in (1, 95, 161) 
order by UserID asc, left(PhotoLabel, 8); 

注:

如果你想提取單身 「自動」(即沒有列出這些),然後用窗口功能。您還可以使用窗口函數來代替in還有:

with t as (
     select UserID, PhotoLabel 
     from dbo.Photos 
     where left(PhotoLabel, 8) in (select distinct top(10) left(PhotoLabel, 8) as date 
            from dbo.Photos 
            order by left(PhotoLabel,8) desc 
            ) 
    ) 
select t.* 
from (select t.*, count(*) over (partition by userid) as cnt 
     from t 
    ) t 
where cnt > 1 
order by userid, left(PhotoLabel, 8); 
+0

我給了1,95和161作爲一個例子。我想消除用戶ID只出現一次的所有行....所以你的第一個答案不起作用,因爲結果集總是有不同的值。 至於你答案的第二部分,我可以修改我現有的代碼而不必編寫窗口函數嗎? – sonnyk2016

+0

@ sonnyk2016。 。 。看看修改後的答案。我重新閱讀這個問題,並認爲這可能是你的意圖。 –

+0

修訂後的答案仍然會生成具有單個UserID的行。我跑了你給的SQL。 – sonnyk2016

0
Select * 
From dbo.Photos 
Where UserID in 
(
    Select UserID 
    From dbo.Photos 
    Group by UserID 
    Having count(UserID)>1 
)