2017-10-27 5 views
1

私のテーブルには、次のようになります:T-SQLは、最後の日付時刻レコード

+---------+------------------------+-------+---------+---------+ 
|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でのレコードとの最大の日付各チャンネルチャネルの総数は一定です。 私のクエリは機能しますが、テーブルが成長するにつれてパフォーマンスが心配です。 3つのほとんど同じクエリを実行することは賢明ではないようです。

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 

これを改善するにはどうすればよいですか?

+0

[T-SQL:MAX(他の列)に基づいて選択するコラム】の可能な重複(https://stackoverflow.com/questions/3680254/t-sql-selecting-column-based-on-maxother -column) –

答えて

3

もう1つのオプションはWITH TIES句を使用しています。サブクエリまたは追加フィールドはありません。

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

あなたがこれを行うことができるか分からなかった。ブリリアント、共有していただきありがとうございます。 – Simon

+0

@シモン私は毎日何かを学びます。それは楽しい部分です:) –

+0

非常にエレガントなソリューション!私はこれを使用するつもりです。ありがとうございます。 :) – gutowskiap

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 
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