消除记录集中的非重复行

时间:2016-09-18 20:41:27

标签: sql-server tsql

下面的T-SQL显示了下面表格中显示的结果。我想以一种排除UserID为1,95和161的行的方式编写T-SQL。这些行只出现一次,我不想将它们包含在结果集中。我想要的是显示UserID出现多次的行。任何帮助将不胜感激。非常感谢你!

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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