2017-12-13 4 views
1

集計関数を使用せずに列idおよびmanager_idをグループ化する方法。 以下はサンプルデータです。 idとmanager_idでグループ化し、created_date descで順序付けしたい。集計関数を使用せずに列idおよびmanager_idをグループ化する方法

id  manager_id manager_mail          created_date 
------  ---------- -------------------------------------- --------------------- 
    1765  2182 [email protected]   2016-08-16 11:35:31 
    1765  2182 [email protected]   2016-08-16 11:35:32 
    1765  2182 [email protected]   2016-07-05 14:01:15 
    1765  2182 [email protected]   2016-07-05 14:00:22 
    1765  2182 [email protected]   2016-07-05 13:59:12 
    1765  2182 [email protected]   2016-07-05 13:58:13 
    1765  2182 [email protected]   2016-06-09 08:34:55 
    1765  2652 [email protected]  2016-04-22 01:37:39 
    1765  2652 [email protected]  2016-02-02 23:00:00 
    1765  2652 [email protected]  2016-01-31 23:00:00 
    1765  2652 [email protected]  2016-01-30 23:00:00 
    1765  2652 [email protected]  2016-01-29 23:00:00 
    1765  2652 [email protected]  2016-01-28 23:00:00 
    1765  2652 [email protected]  2016-01-27 23:00:00 
    1765  2652 [email protected]  2016-01-26 23:00:00 
    1765  2652 [email protected]  2016-01-25 23:00:00 
    1765  2652 [email protected]  2016-01-24 23:00:00 
    1765  2652 [email protected]  2016-01-23 23:00:00 
    1765  2652 [email protected]  2016-01-22 23:00:00 
    1765  2652 [email protected]  2016-01-21 23:00:00 
    1765  2652 [email protected]  2016-01-20 23:00:00 
    1765  2652 [email protected]  2016-01-08 23:00:00 
    1765  2652 [email protected]  2015-12-15 11:51:57 
    1765  1702 [email protected]  2015-12-15 11:51:57 
+0

次使用することができますidあたりとmanager_idあなたは私たちにあなたが期待する出力、またはむしろ、その出力の小さなスナップショットを表示することができますか?あなたの質問の1つの解釈は、必要なのは 'ORDER BY'節です。これは簡単なことですが、あなたの出力がこれを明確にすることが分かります。 –

答えて

0

ここに集約を使用する代わりに、各id/manager_idペアの最新のレコードを識別する副問合せを使用することです:

SELECT * 
FROM yourTable t1 
WHERE created_date = (SELECT MAX(created_date) FROM yourTable t2 
         WHERE t1.id = t2.id AND t1.manager_id = t2.manager_id); 

しかし、実際に私がGROUP BYとなるだろう:

SELECT t1.* 
FROM yourTable t1 
INNER JOIN 
(
    SELECT id, manager_id, MAX(created_date) AS max_created_date 
    FROM yourTable 
    GROUP BY id, manager_id 
) t2 
    ON t1.id = t2.id AND 
     t1.manager_id = t2.manager_id AND 
     t1.created_date = t2.max_created_date; 
+0

投稿ありがとう!それは私の場合に働いた –

0

集計関数を使用しない別のアプローチでは、自己(左)結合を使用します。に基づいて最新の行を取得するにはクエリ

select a.* 
from demo a 
left join demo b 
on a.id = b.id 
and a.manager_id = b.manager_id 
and a.created_date < b.created_date 
where b.id is null 

Demo

関連する問題