2

我有这个查询可以正常工作。但是,我遇到了在 [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
4

3 回答 3

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;
于 2012-10-11T17:21:07.070 回答
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]
于 2012-10-11T17:21:42.207 回答
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
于 2012-10-11T17:21:12.910 回答