سؤال

I have this query that works as it should. However, I am having a problem with the query returning identical int values under the [id2] column. I need help in only grabbing one instance of the value and ignoring the other. Basically grab a unique [id2]. Any help would be greatly appreciated. Also, if you need clarification let me know.

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

Edit 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

Should be:

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
هل كانت مفيدة؟

المحلول

;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]

نصائح أخرى

You may need to adjust the ORDER BY part below depending on how you want to choose which row to return.

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;

You seem to be looking for the earliest record of the list for a given (id2, name) and the following query would retrieve them:

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top