HOW TO: SQL Server select distinct field based on max value in other field

故事扮演 提交于 2020-01-24 19:14:41

问题


id   tmpname      date_used        tkt_nr
---|---------|------------------|--------|
1  | template| 04/03/2009 16:10 | 00011  |
2  | templat1| 04/03/2009 16:11 | 00011  |
5  | templat2| 04/03/2009 16:12 | 00011  |
3  | diffname| 03/03/2009 15:11 | 00022  |
4  | diffname| 03/03/2009 16:12 | 00022  |
6  | another | 03/03/2009 16:13 | NULL   |
7  | somethin| 24/12/2008 11:12 | 00023  |
8  | name    | 01/01/2009 12:12 | 00026  |

I would like to have the result:

id   tmpname      date_used        tkt_nr
---|---------|------------------|--------|
5  | templat2| 04/03/2009 16:12 | 00011  |
4  | diffname| 03/03/2009 16:12 | 00022  |
7  | somethin| 24/12/2008 11:12 | 00023  |
8  | name    | 01/01/2009 12:12 | 00026  |

So what I'm looking for is to have distinct tkt_nr values excluding NULL, based on the max value of datetime.

I have tried several options but always failed

SELECT *
FROM  templateFeedback a 
JOIN (
      SELECT ticket_number, MAX(date_used) date_used
      FROM   templateFeedback
      GROUP BY ticket_number
     ) b 
ON a.ticket_number = b.ticket_number AND a.date_used = b.date_used

I would appreciate any help. Unfortunately I need the code to be compatible with SQL Server.


回答1:


I've stopped doing things this way since I discovered windowing functions. Too often, there are two records with the same timestamp and I get two records in the resultset. Here's the code for tSQL. Similar for Oracle. I don't think mySQL supports this yet.

Select id, tmpname, date_used, tkt_nbr
From 
(
    Select id, tmpname, date_used, tkt_nbr,
        rownum = Row_Number() Over (Partition by tkt_nbr Order by date_used desc)
) x
Where row_num=1


来源:https://stackoverflow.com/questions/12570747/how-to-sql-server-select-distinct-field-based-on-max-value-in-other-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!