T-SQL按最早的日期和唯一的类别选择行 [英] T-SQL select rows by oldest date and unique category
本文介绍了T-SQL按最早的日期和唯一的类别选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Microsoft SQL.我有一个表,其中包含按两个不同类别存储的信息和一个日期.例如:
I'm using Microsoft SQL. I have a table that contains information stored by two different categories and a date. For example:
ID Cat1 Cat2 Date/Time Data
1 1 A 11:00 456
2 1 B 11:01 789
3 1 A 11:01 123
4 2 A 11:05 987
5 2 B 11:06 654
6 1 A 11:06 321
我想为Cat1和Cat2的每种唯一组合提取一行,并且我需要具有最早日期的那一行.在上面,我希望ID = 1、2、4和5.
I want to extract one line for each unique combination of Cat1 and Cat2 and I need the line with the oldest date. In the above I want ID = 1, 2, 4, and 5.
谢谢
推荐答案
Have a look at row_number()
on MSDN.
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY date_time, id) rn
FROM mytable
) q
WHERE rn = 1
(在 SQL小提琴上运行代码)
这篇关于T-SQL按最早的日期和唯一的类别选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文