简体   繁体   中英

How does select distinct on order by work in postgresql?

Tablex:

| ID |  SITE| TIME  | TYPE|
|----|------|-------|-----|
| aa | 100  | 12-18 | fo  |
| aa | 101  | 12-10 | ba  |
| bb | 102  | 12-10 | fo  |
| cc | 100  | 12-09 | ba  |
| cc | 109  | 12-01 | fo  |
| dd | 100  | 12-08 | fo  |

The fo equal 2, and ba equal 1.
I want to order by type and insert it to another table.

INSERT INTO "NUtable"
SELECT DISTINCT ON("ID")
*
FROM
TABLEX
ORDER BY
"ID","SITE","TIME",(CASE "TYPE" WHEN 'fo' then 2
WHEN 'ba' then 1
ELSE NULL END
) DESC

The SQL seems work fine. However, the result got wrong in some rows. Why so?

Here is the example for cc got wrong result: http://sqlfiddle.com/#!17/0c0e4/2

The result should be

+----+------+-------+------+
| ID | SITE | TIME  | TYPE |
+----+------+-------+------+
| aa |  100 | 12-18 | fo   |
| bb |  102 | 12-10 | fo   |
| cc |  109 | 12-01 | fo   |
| dd |  100 | 12-08 | fo   |
+----+------+-------+------+

instead of

+----+------+-------+------+
| ID | SITE | TIME  | TYPE |
+----+------+-------+------+
| aa |  100 | 12-18 | fo   |
| bb |  102 | 12-10 | fo   |
| cc |  100 | 12-09 | ba   |
| dd |  100 | 12-08 | fo   |
+----+------+-------+------+

You need to order by type as the second key:

SELECT DISTINCT ON ("ID") x.*
FROM TABLEX x
ORDER BY "ID",
         (CASE "TYPE" WHEN 'fo' THEN 2 WHEN 'ba' then 1
               ELSE NULL
          END) DESC,
         "SITE", "TIME";

DISTINCT ON takes the first row that it encounters for each "ID" . You want that row to have a particular type, so the logic for the type should be part of the ORDER BY .

The sorting of the rows is in priority of the order of the columns given after ORDER BY so in your example it works as expected since you order is id, site, ...

If you want to achieve the expected result you need to move type to second in order

ORDER BY id, (CASE “TYPE”...

You should also switch inside the case so that 'fo' is 1 and 'ba' is 2

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