简体   繁体   English

如何使用查询在表中选择最新日期

[英]How can I chose the latest date in a table using query

This is what I did, which is wrong.这就是我所做的,这是错误的。 My date field is stored as (MM/DD/YYYY)我的日期字段存储为 (MM/DD/YYYY)

Select Name,Family,ID,max(Dates) from MyTable group by name,family

If Dates is a TEXT column containing values stored as MM/DD/YYYY , calling MAX() on it doesn't produce the latest date because Sqlite will do an alphanumeric sort on the column, which will sort by month first.如果Dates是包含存储为MM/DD/YYYY的值的TEXT列,则对其调用MAX()不会产生最新日期,因为 Sqlite 将对列进行字母数字排序,首先按月份排序。

You need to properly convert the Dates TEXT values into DATE values and then when you call MAX() on the DATE values, Sqlite will sort the way you expect and produce the latest date value.您需要将 Dates TEXT 值正确转换为DATE值,然后当您对 DATE 值调用 MAX() 时,Sqlite 将按照您期望的方式进行排序并生成最新的日期值。

DATE values can be created using DATE() but the parameter to DATE() needs to be a date string in ISO format ( YYYY-MM-DD ).可以使用DATE()创建 DATE 值,但 DATE() 的参数需要是ISO格式 ( YYYY-MM-DD ) 的日期字符串。 So, we need to parse out the existing TEXT string values using substr(), then build an ISO date from the parsed-out date part components, then finally pass that ISO date into DATE() as the parameter.因此,我们需要使用 substr() 解析出现有的 TEXT 字符串值,然后从解析出的日期部分组件构建一个 ISO 日期,最后将该 ISO 日期作为参数传递给 DATE()。

But, a side effect of this is that the query output will now show the max date in ISO format, so if you need the date in the original format, you would need to include that separately.但是,这样做的副作用是查询 output 现在将以 ISO 格式显示最大日期,因此如果您需要原始格式的日期,则需要单独包含它。

So, something like this:所以,像这样:

SELECT Name, Family, ID, Dates, MAX(DATE(SUBSTR(Dates, 7, 4) || '-' || SUBSTR(Dates, 1, 2) || '-' || SUBSTR(Dates, 4, 2))) FROM MyTable

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

相关问题 如何根据最新的 Date 和 Time OR Date_Time 列查询 SQL 的最新记录? - How do I query SQL for the latest record based on latest Date and Time OR Date_Time columns? 我如何获得Linq的最新截止日期 - How i can get the latest due date with Linq 如何在NHibernate中使用sql查询创建表? - How Can I Do Create Table by using sql query in NHibernate? 如何查询具有最新日期的记录作为另一个 linq 查询的一部分 - how to query a record with latest date as part of another linq query 使用LINQ按最新日期获取所有记录(从单个表中获取) - Get all records (from single table) by latest date using LINQ 如何使用 LINQ 从对象集合中获取最新日期? - How do I get the latest date from a collection of objects using LINQ? 如何对行进行分组并选择要在数据表中显示的最新日期 - How to group rows and select latest date to display in a data table 如何在不使用表两次的情况下加速LINQ查询? - How can I speed up my LINQ query without using a table twice? 如何使用C#中的textbox值查询mySql表? - How can I query a mySql table by using the value of textbox in C#? 如何仅使用sql查询从Excel中填充SQL Server表? - How can I fill SQL Server table from excel only using sql query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM