简体   繁体   中英

How to select the key of a group order by column a where a column b is not ordering

is it possible to select the id of the groups ordered accending by column line_to where a column obj_id is not also ordered accending?

So the result for my test-data should be 200 because line_no 2 with obj_id 25 is followed by line_no 3 with obj_id 12. And 300 because line_no 1 with obj_id 11 is followed by line_no 2 with obj_id 10.

Database is PostgreSQL 9.2

Thanks in advance

DROP TABLE data;

CREATE TABLE data (id int NOT NULL, line_no int NOT NULL, obj_id int, PRIMARY KEY (id, line_no));

INSERT INTO data VALUES 
  (100, 1, 11),
  (100, 2, 12),
  (100, 3, 15), 
  (100, 4, 18), 
  (200, 1, 11),
  (200, 2, 25),
  (200, 3, 12), 
  (200, 4, 18),
  (300, 1, 11),
  (300, 2, 10),
  (300, 3, 12), 
  (300, 4, 18),
  (400, 1, 11),
  (400, 2, 23),
  (400, 3, 35), 
  (400, 4, 38);

SELECT id FROM data GROUP BY id;  -- must be extended, the result should be 200 and 300

一些简单的SQL可以解决问题。

SELECT DISTINCT d1.id FROM data d1, data d2 WHERE d2.id = d1.id AND d2.line_no > d1.line_no and d2.obj_id < d1.obj_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM