T-SQL获取最后一个日期时间记录

时间:2017-10-27 17:44:18

标签: sql database tsql sql-server-2014

我的表格如下:

+---------+------------------------+-------+---------+---------+
|channel  |date                    |code   |comment  |order_id |
+---------+------------------------+-------+---------+---------+
|1        |2017-10-27 12:04:45.397 |2      |comm1    |1        |
|1        |2017-10-27 12:14:20.997 |1      |comm2    |1        |
|2        |2017-10-27 12:20:59.407 |3      |comm3    |1        |
|2        |2017-10-27 13:14:20.997 |1      |comm4    |1        |
|3        |2017-10-27 12:20:59.407 |2      |comm5    |1        |
|3        |2017-10-27 14:20:59.407 |1      |comm6    |1        |
+---------+------------------------+-------+---------+---------+

我希望结果如下:

+---------+------------------------+-------+---------+
|channel  |date                    |code   |comment  |
+---------+------------------------+-------+---------+
|1        |2017-10-27 12:14:20.997 |1      |comm2    |
|2        |2017-10-27 13:14:20.997 |1      |comm4    |
|3        |2017-10-27 14:20:59.407 |1      |comm6    |
+---------+------------------------+-------+---------+

始终为1条记录,每个频道的order_id = x和最大日期。通道总数是不变的。 我的查询有效,但随着表的增长,我担心性能。做三个几乎完全相同的查询似乎并不聪明。

select
    *
from
    (select top(1)
        channel,
        date,
        code,
        comment
    from
        status
    where
        channel = 1 and
        order_id = 1 and
        cast(date as date) = '2017-10-27'
    order by 
        date desc) channel1
union
select 
    *
from
    (select top(1)
        channel,
        date,
        code,
        comment
    from
        status
    where
        channel = 2 and
        order_id = 1 and
        cast(date as date) = '2017-10-27'
    order by 
        date desc) channel2
union
select 
    *
from
    (select top(1)
        channel,
        date,
        code,
        comment
    from
        status
    where
        channel = 3 and
        order_id = 1 and
        cast(date as date) = '2017-10-27'
    order by 
        date desc) channel3

我该如何改善这个?

3 个答案:

答案 0 :(得分:3)

另一种选择是使用WITH TIES子句。没有子查询或额外字段。

Select top 1 with ties *
 From  YourTable
 Order By Row_Number() over (Partition By channel order by date desc)

答案 1 :(得分:2)

尝试使用ROW_NUMBER()函数和派生表。它会为你节省很多麻烦。尝试:

select channel
       ,date
       ,code
       ,comment
from
(select *
       ,row_number() over(partition by channel order by code asc) rn --probably don't need asc since it is ascending by default
from mytable) t
where t.rn = 1

答案 2 :(得分:0)

假设您想要每个频道的最新行,这将有效。

SELECT *
FROM (
    SELECT
        ROW_NUMBER() OVER (PARTITION BY s.channel ORDER BY [date] DESC) AS rn,
        *
    FROM [status] AS s
) AS t
WHERE t.rn = 1
相关问题