当列具有相同值但第二列具有不同值时,如何获得单个结果

时间:2018-02-08 04:43:24

标签: sql mysqli

我有这张桌子

Id  VendorId    ClaimRequestDate
1   5           2017-12-14 00:00:00.000
2   5           2018-02-02 00:00:00.000
7   5           2018-02-07 11:08:25.257

我希望我的结果仅显示每个VendorId的最新日期从2018年2月2日之后的日期开始

我现在所做的

    SELECT DISTINCT
        [Project1].[Id] AS [Id], 
        [Project1].[VendorId] AS [VendorId], 
        [Project1].[ClaimRequestDate] AS [ClaimRequestDate]
        FROM ( SELECT 
            [Extent1].[Id] AS [Id], 
            [Extent1].[VendorId] AS [VendorId], 
            [Extent1].[ClaimRequestDate] AS [ClaimRequestDate]
            FROM [dbo].[Claim] AS [Extent1]
            WHERE [Extent1].[ClaimRequestDate] >= '2018-02-02 00:00:00.000'
        )  AS [Project1]
        ORDER BY [Project1].[ClaimRequestDate] DESC

但我的结果是

Id  VendorId    ClaimRequestDate
7   5           2018-02-07 11:08:25.257
2   5           2018-02-02 00:00:00.000

有人可以帮助我吗

2 个答案:

答案 0 :(得分:0)

尝试以下SQL:

select aa.* from [Claim] as aa inner join
(
select [VendorId], max([Id]) as maxId from [Claim]
where [ClaimRequestDate] >= '2018-02-03 00:00:00'
group by [VendorId]
) as bb on aa.[Id] = bb.[maxId]

答案 1 :(得分:0)

您的查询中存在树问题。一个是

 WHERE [Extent1].[ClaimRequestDate] >= '2018-02-02 00:00:00.000'

行是> =应该是">"第二个是您的查询从2018-02-02之后的日期获取所有行如果vendorId具有多个值,则Query将返回您可以尝试此

SELECT * FROM Claim c
    where ClaimRequestDate  IN  (select MAX(ClaimRequestDate) from claim c1 
       where c.vendorId =c1.vendorId and c1.Claimrequestdate >'2018.02.02')

当您的vendorId具有超过相同的max(Claimrequestdate)将返回所有这些时,第三个是此查询

Id  VendorId    ClaimRequestDate
 1   5           2017-12-14 00:00:00.000
 2   5           2018-02-02 00:00:00.000
 7   5           2018-02-07 11:08:25.257
 8   5           2018-02-07 11:08:25.257

返回

Id  VendorId    ClaimRequestDate
 7   5           2018-02-07 11:08:25.257
 8   5           2018-02-07 11:08:25.257

由于这些原因,我建议使用此查询

SELECT * FROM Claim c
where CAST(ClaimRequestDate AS VARCHAR)+ CAST(ID AS VARCHAR)   IN  (select 
MAX(CAST(ClaimRequestDate AS VARCHAR)+ CAST(ID AS VARCHAR)) from claim c1 
where c.vendorId =c1.vendorId and c1.Claimrequestdate >'2018.02.02'
)