我有一张看起来像的桌子
id cat data
--------------------
1 1 foo
2 1 bar
3 1 baz
4 2 some
5 2 random
6 3 Data 1
7 2 data
8 3 Data 2
9 3 Data 3
我想要最后 3id
秒和data
每个类别的单行,比如
cat id1 data1 id2 data2 id3 data3
-----------------------------------------------------
1 1 foo 2 bar 3 baz
2 4 some 5 random 7 data
3 6 Data 1 8 Data 2 9 Data 3
我已经尝试了以下方法:
id
获取每个最高的数据cat
:SELECT id, data FROM tbl t1 WHERE EXISTS ( SELECT 1 FROM tbl t2 WHERE t1.cat = t2.cat GROUP BY t2.cat HAVING MAX(t2.id) = t1.id )
获取每个 s 中第二高的数据:
id
cat
SELECT id, data FROM tbl t1 WHERE EXISTS ( SELECT 1 FROM tbl t2 WHERE t1.cat = t2.cat AND NOT EXISTS ( -- Not the highest value SELECT 1 FROM tbl t3 WHERE t1.cat = t3.cat GROUP BY t3.cat HAVING MAX(t3.id) = t2.id ) GROUP BY t2.cat HAVING MAX(t2.id) = t1.id )
获取每个3 rd最高的数据:
id
cat
SELECT id, data FROM tbl t1 WHERE EXISTS ( SELECT 1 FROM tbl t2 WHERE t1.cat = t2.cat AND NOT EXISTS ( -- id is not 2nd highest SELECT 1 FROM tbl t3 WHERE t1.cat = t3.cat AND NOT EXISTS ( -- id is not the highest SELECT 1 FROM tbl t4 WHERE t1.cat = t4.cat GROUP BY t4.cat HAVING MAX(t4.id) = t3.id ) GROUP BY t3.cat HAVING MAX(t3.id) = t2.id ) AND NOT EXIST ( -- not the highest id SELECT 1 FROM tbl t5 WHERE t1.cat = t5.cat GROUP BY t5.cat HAVING MAX(t5.id) = t2.id ) GROUP BY t2.cat HAVING MAX(t2.id) = t1.id )
现在,加入整个事情。但我相信存在更好的解决方案。它是什么?
PS:我必须用 Informix 来做