2016-11-22 5 views
0

同様の質問(123 ...)で投稿をチェックしましたが、MySQL57(mysql-installer-community-5.7.13.0.msi) 。私がしたいことは逆方向(テーブルの下から上へ)で "グループ化"することです。本当に次のクエリがうまくいかない理由を理解できません。私は何を得るMySQLを逆順にする

use db; 

# create the table. k guarantees increase. 
CREATE TABLE `db`.`test` (
    `k` INT NOT NULL, 
    `a` INT NULL, 
    `b` INT NULL, 
    `c` INT NULL, 
PRIMARY KEY (`k`)); 

# populate data 
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('1', '1', '10', '100'); 
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('2', '2', '20', '200'); 
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('3', '1', '10', '300'); 
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('4', '3', '30', '700'); 
INSERT INTO `db`.`test` (`k`, `a`, `b`, `c`) VALUES ('5', '3', '30', '800'); 

# want to query the last entry of each unique a+b 
Select * From 
    (Select * From test Order By k Desc) As t 
    Group By t.a, t.b; 

k a b c 
1 1 10 100 
2 2 20 200 
4 3 30 700 

ですが、私が欲しいのは、順序は重要ではありません、以下の通りです。

k a b c 
5 3 30 800 
3 1 10 300 
2 2 20 200 

答えて

2

group byはまったく必要ありません。インテリジェントなフィルタリングが必要なだけです:

Select t.* 
From test t 
where t.k = (select max(t2.k) 
      from test t2 
      where t2.a = t.a and t2.b = t.b 
      ); 
+0

魅力的なように働きます! – brewphone