从给定日期范围sql server获取最大日期和最大日期之前的确切日期

时间:2015-06-11 14:34:23

标签: sql datetime

我在表格中有日期栏

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年6月1日
采用WordPress
2015年6月6日
2015-06-25


2015-06-06在一栏中 2015-06-09在其他栏目中

也是同一列
2015-06-06
2015-06-25

我试过了:

s = sum(lst, DummyItem())

但无法访问
2015-06-06在一栏中 2015-06-09在其他栏目中

3 个答案:

答案 0 :(得分:1)

坚持使用ISO标准日期格式和内置类型:

SELECT DISTINCT CONVERT(DATE, e.event_timestamp) myDate
FROM events e
WHERE e.event_timestamp Between '2015-06-01T11:14:40' AND '2015-06-11T11:14:40'

这可能会解决您的问题。

答案 1 :(得分:0)

使用sql server

WITH cteEvents AS 
(
    SELECT
        CONVERT(VARCHAR,event_timestamp,101) event_date,
        RANK()OVER(ORDER BY CONVERT(VARCHAR,event_timestamp,101) DESC) rnk

    FROM
        events
    WHERE
        event_timestamp BETWEEN '01-Jun-15 11:14:40 AM'
                            AND     '11-Jun-15 11:14:40 AM'
    GROUP BY 
        CONVERT(VARCHAR,event_timestamp,101)
)
SELECT 
    event_date, 
    (SELECT event_date FROM cteEvents WHERE rnk = 2),  
    (SELECT event_date FROM cteEvents WHERE rnk = 1) 
FROM 
    cteEvents

答案 2 :(得分:0)

谢谢(user1221684),这工作很精细,

WITH cteEvents AS 
(
    SELECT
        CONVERT(VARCHAR,event_timestamp,103) event_date,
        RANK()OVER(ORDER BY CONVERT(VARCHAR,event_timestamp,103) DESC) rnk
    FROM
        events
    WHERE
        event_timestamp BETWEEN '01-Jun-15 11:14:40 AM'
                            AND     '11-Jun-15 11:14:40 AM'
    GROUP BY 
        CONVERT(VARCHAR,event_timestamp,103)
)
SELECT 
    max(event_date), 
    (SELECT event_date FROM cteEvents WHERE rnk = 2)
    --,(SELECT event_date FROM cteEvents WHERE rnk = 1) 
FROM 
    cteEvents

这也很好

SELECT top 2 myDate
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
order by myDate desc