123 201501 201501 568 200601 201512 解决方案 如果我们可以假设PostDate永远不会大于DateOfDeath那么简单group by将: SELECT ID_NO,DateOfDeath,Max(PostDate) as PostDate FROM yourtable GROUP BY ID_NO,DateOfDeath 假设Microsoft SQL Server, ROW_NUMBER 功能 [ ^ ]可以解决问题: WITH cteOrderedData As ( SELECT ID_NO, DateOfDeath, PostDate, ROW_NUMBER() OVER ( PARTITION BY ID_NO ORDER BY CASE WHEN DateOfDeath = PostDate 那么 0 ELSE 1 END , PostDate DESC ) As RN FROM YourTable ) SELECT ID_NO, DateOfDeath, PostDate FROM cteOrderedData WHERE RN = 1 ; Hi there,I have the following datasetID_NO DateOfDeath PostDate123 201501 201412123 201501 201501568 200601 201504568 200601 201512I need to select the ID_no when the DateOfDeath is equal to the PostDate. If it is not then it should select the ID_no with the maximum date.The result should be:ID_NO DateOfDeath PostDate123 201501 201501568 200601 201512 解决方案 If we can assume that PostDate can never be greater than DateOfDeath then simple group by will do:SELECT ID_NO, DateOfDeath, Max(PostDate) as PostDate FROM yourtable GROUP BY ID_NO, DateOfDeathAssuming Microsoft SQL Server, the ROW_NUMBER function[^] will do the trick:WITH cteOrderedData As( SELECT ID_NO, DateOfDeath, PostDate, ROW_NUMBER() OVER ( PARTITION BY ID_NO ORDER BY CASE WHEN DateOfDeath = PostDate THEN 0 ELSE 1 END, PostDate DESC ) As RN FROM YourTable)SELECT ID_NO, DateOfDeath, PostDateFROM cteOrderedDataWHERE RN = 1; 这篇关于SQL选择日期相等或给出最大日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-30 23:48