SQL Server:从具有相同标识符的两行中选择一行

时间:2018-10-16 03:21:57

标签: sql sql-server sql-server-2008

我在SQL Server中有一个表,其中包含100多行。

以下是我要获取的数据的示例:

51206 69975314 InWork NULL
52160 70064509 Close  2018-05-10 12:52:49.000
52109 70071378 InWork NULL

如果id包含2个不同的状态,请选择状态InWork,或在最长时间内确定id。

CREATE TABLE [dbo].[#RESULT_TABLE_X]
(
    [ID_ADD] NVARCHAR(50) NULL,
    [ID] NVARCHAR(50) NULL,
    [STATUS] NVARCHAR(50) NULL,
    [TIME] DATETIME NULL
) ON [PRIMARY]

INSERT INTO [dbo].[#RESULT_TABLE_X] 
VALUES ('51206', '69975314', 'InWork', NULL),
       ('52160', '70064509', 'Close', '2018-10-05 10:52:49.000'),
       ('52160', '70064509', 'Close', '2018-10-05 12:52:49.000'),
       ('52109', '70071378', 'InWork', NULL),
       ('51887', '70071378', 'Close', '2018-10-06 10:52:49.000')

我使用了下面的查询,但没有为我显示所需的结果

SELECT
    ID_ADD, ID, STATUS,TIME
FROM
    [dbo].[#RESULT_TABLE_X]
WHERE
    STATUS NOT IN ('Close')
ORDER BY
    STATUS, ID 

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

尝试一下:

    CREATE TABLE [dbo].[#RESULT_TABLE_X]
    (
        [ID_ADD] NVARCHAR(50) NULL,
        [ID] NVARCHAR(50) NULL,
        [STATUS] NVARCHAR(50) NULL,
        [TIME] DATETIME NULL
    ) ON [PRIMARY]

    INSERT INTO [dbo].[#RESULT_TABLE_X] 
    VALUES ('51206', '69975314', 'InWork', NULL),
           ('52160', '70064509', 'Close', '2018-10-05 10:52:49.000'),
           ('52160', '70064509', 'Close', '2018-10-05 12:52:49.000'),
           ('52109', '70071378', 'InWork', NULL),
           ('51887', '70071378', 'Close', '2018-10-06 10:52:49.000')

    ;with cte
    As(

        Select Max(ID_Add) as ID_ADD, [ID] as ID
        from [dbo].[#RESULT_TABLE_X] 
        Group by ID
    )

    Select r.ID_ADD,r.Id,MAX(Status) as Status, Max(Time) as Time from cte c
    INNER JOIN [dbo].[#RESULT_TABLE_X] r on c.ID_ADD=r.ID_ADD and c.Id=r.Id
    Group by r.Id ,r.ID_Add

    Drop Table [dbo].[#RESULT_TABLE_X] 

答案 1 :(得分:0)

使用ROW_NUBMER()来根据ID_ADD和ID生成运行号

SELECT *
FROM
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY ID_ADD, ID 
                                          ORDER BY TIME DESC)
    FROM   #RESULT_TABLE_X
) D
WHERE D.RN = 1