忽略特定列中的相同值

时间:2012-10-11 17:01:52

标签: sql sql-server tsql sql-server-2012 distinct-values

我有这个查询可以正常工作。但是,我遇到的问题是在[id2]列下返回相同的int值。我需要帮助只抓取一个值的实例而忽略另一个。基本上抓住一个独特的[id2]。任何帮助将不胜感激。另外,如果您需要澄清,请告诉我。

SELECT [id],[id1]
 ,[id2]
 ,[name]
 ,[date]
 ,[user]     
FROM [MyDatabase.table]
Where [date]>= dateadd(day,datediff(day,0,getdate()),-5)
ORDER BY [cid]

修改1:

id1       id2    name        time                user
6466    171477  item1 2012-10-10 07:08:48.000   user1
6469    171477  item1 2012-10-10 07:11:01.000   user1
6468    171477  item1 2012-10-10 07:10:37.000   user1
6465    171477  item1 2012-10-10 07:07:43.000   user1
6464    171477  item1 2012-10-10 07:06:58.000   user1
6467    171477  item1 2012-10-10 07:09:35.000   user1
6474    173026  item2 2012-10-10 10:20:21.000   user2
6478    173297  item3 2012-10-10 11:31:55.000   user3
6472    175445  item4 2012-10-10 07:18:17.000   user1
6460    175977  item5 2012-10-08 07:42:39.000   user4
6473    176253  item6 2012-10-10 10:18:21.000   user2
6471    176253  item6 2012-10-10 10:15:03.000   user2
6470    176253  item6 2012-10-10 10:14:34.000   user2

应该是:

id1     id2    name        time                user
6466    171477  item1 2012-10-10 07:08:48.000   user1
6474    173026  item2 2012-10-10 10:20:21.000   user2
6478    173297  item3 2012-10-10 11:31:55.000   user3
6472    175445  item4 2012-10-10 07:18:17.000   user1
6460    175977  item5 2012-10-08 07:42:39.000   user4
6473    176253  item6 2012-10-10 10:18:21.000   user2

3 个答案:

答案 0 :(得分:2)

您可能需要调整下面的ORDER BY部分,具体取决于您要选择返回哪一行。

WITH cteRowNum AS (
    SELECT id1, id2, name, time, user,
           ROW_NUMBER() OVER(PARTITION BY id2 ORDER BY time) AS RowNum
        FROM MyDatabase.Table
)
SELECT id1, id2, name, time, user
    FROM cteRowNum
    WHERE RowNum = 1;

答案 1 :(得分:1)

;WITH tbl_online AS (
SELECT [id],[r_id]
 ,[cid]
 ,[name]
 ,[date]
 ,[user] ,ROW_NUMBER () OVER (
PARTITION BY [cid] ORDER BY [cid] ) AS Rnum
FROM [MyDatabase.table]
Where [date]>= dateadd(day,datediff(day,0,getdate()),-5)   )
SELECT *  FROM tbl_online WHERE Rnum !>1
ORDER BY [cid]

答案 2 :(得分:0)

您似乎正在寻找给定(id2,name)列表的最早记录,以下查询将检索它们:

SELECT a.*
FROM 
    YourTable a
    JOIN 
    (
        SELECT MIN(id1) as id1, id2, name FROM YourTable GROUP BY id2, name
    ) as b
    ON a.id1 = b.id1