简体   繁体   English

T-SQL,比较记录属性,然后比较后续日期

[英]T-SQL, Compare Record Property, Then Suusequent Date Compare

I have a table in SQL, and it looks like this: 我在SQL中有一个表,它看起来像这样:

FOO   BAR   DateTime
---   ---   ------
FOO1  BAR1  4/25/2014
FOO2  BAR2  4/24/2014
........

to any n number of records in the above format. 到上述格式的任意n个记录。

I am trying to write a query that first returns all records that meet two property conditions, say all the records where FOO = FOO1 and BAR = BAR1, then with those results, return the record that has the most recent value out of the DateTime column. 我正在尝试编写一个查询,该查询首先返回满足两个属性条件的所有记录,说所有记录,其中FOO = FOO1和BAR = BAR1,然后使用这些结果,从DateTime列中返回具有最新值的记录。 There can be multiple records where FOO = FOO1 and BAR = BAR1, and I am trying to get the most recent based on the datetime field value. 可能有多个记录,其中FOO = FOO1和BAR = BAR1,我正在尝试基于datetime字段值获取最新记录。

Well if I understood the request correctly (and it is SQL Server) it would be something like this: 好吧,如果我正确理解了该请求(它是SQL Server),它将是这样的:

SELECT TOP 1 FOO, BAR, DateTime
FROM Table 
WHERE FOO='FOO1' AND BAR='BAR1'
ORDER BY DateTime DESC

WHERE condition limits the set, ORDER BY sorts the set in descending order by date and TOP 1 selects the most recent record. 在条件限制集合的情况下,ORDER BY按日期降序对集合进行排序,而TOP 1选择最近的记录。

SELECT FOO, BAR, Datetime FROM table WHERE Foo = 'FOO1' and Bar = 'BAR1' 
and DateTime = (SELECT MAX(DATETIME) from table WHERE Foo = 'FOO1' and Bar = 'BAR1')

Probably this...or any other answer...haha 可能是这个...或其他答案...哈哈

This should give you the answer in almost any dialect of SQL 这应该为您提供几乎所有SQL方言的答案

select FOO, BAR, MAX(DateTime) from 
table_name
where 
FOO = 'FOO1'
and BAR = 'BAR1'
group by FOO, BAR

As you said you need just one data , the following query should do it. 正如您所说的,您只需要一个数据,下面的查询就可以完成。 Since you have tagged your question with MySql so its mysql solution. 由于您已经用MySql标记了您的问题,因此它是mysql解决方案。

select FOO, BAR, MAX(DateTime) from 
table
where 
FOO = 'FOO1'
and BAR = 'BAR1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM