【问题标题】:how to access last two dates sql server如何访问最后两个日期sql server
【发布时间】:2015-08-27 13:11:21
【问题描述】:

我在表格中有日期列

ColumnName: event_timestamp
2015-06-01 15:23:31.000
2015-06-01 15:25:21.000
2015-06-03 09:00:41.000
2015-06-03 09:14:49.000
2015-06-03 09:15:03.000
2015-06-03 09:15:23.000
2015-06-06 08:40:06.000
2015-06-06 08:40:19.000
2015-06-06 11:13:35.000
2015-06-06 11:13:53.000
2015-06-06 11:15:04.000
2015-06-06 11:15:30.000
2015-06-09 15:08:13.000
2015-06-09 15:08:33.000
2015-06-09 15:08:45.000
2015-06-09 15:09:05.000

预期输出

2015-06-06
2015-06-09

我试过但失败了

SELECT CONVERT(datetime,MAX(myDate),103),      
               (MAX(CONVERT(datetime,mydate,103)))-1 as DT 
FROM (
       SELECT DISTINCT (CONVERT(VARCHAR,events.event_timestamp, 103)) myDate
       FROM events 
       Where event_timestamp Between '01-Jun-15 11:14:40 AM' 
                     AND '11-Jun-15 11:14:40 AM'
     ) tbl

【问题讨论】:

  • 不清楚你在问什么?您的第二个预期输出是什么意思?
  • 最大日期是 2015 年 6 月 9 日,我还想从给定的列数据中获得确切的上一个日期,即 2015 年 6 月 6 日。
  • 你为什么放......“我只想要”......然后是四个日期......然后是“还有同一列......还有两个日期......”哪一个是你的预期....澄清并编辑您的问题
  • 哪个DB、mysql、Sql Server?
  • sql server 2008,好的,我只想要 2015-06-09, 2015-06-06

标签: sql sql-server sql-server-2008 tsql datetime


【解决方案1】:

使用带有 Desc 的 Group By 和 Order By 子句,然后获取前 2 条记录

Select TOP 2 CONVERT(date, datecol) 
From #t
Group By CONVERT(date, datecol)
Order By CONVERT(date, datecol) Desc

See Working Example

【讨论】:

    【解决方案2】:

    你可以这样做:

    -- grabs top 2 descending by date
    select top 2 distinctDates
    from (
        -- gets the distinct dates between your date range
        select distinct convert(date, mydate) as distinctDates
        FROM events e
        where e.timestamp Between '01-Jun-15 11:14:40 AM' AND '11-Jun-15 11:14:40 AM'
    ) dt
    order by distinctDates desc
    

    【讨论】:

      【解决方案3】:

      一个简单的方法是执行“GROUP BY”和“LIMIT 2”。您将希望按日期分组(记住忽略时间),然后将结果限制为 2。这是这两个的链接。

      限制:http://www.w3schools.com/sql/sql_top.asp 分组:https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-28
        相关资源
        最近更新 更多