简体   繁体   English

如何在 postgresql 中按顺序选择不同的工作?

[英]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. fo 等于 2,ba 等于 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. SQL 似乎工作正常。 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这是 cc 得到错误结果的示例: 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" . DISTINCT ON取每个"ID"遇到的第一行。 You want that row to have a particular type, so the logic for the type should be part of the ORDER BY .您希望该行具有特定类型,因此该类型的逻辑应该是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, ...行的排序优先于 ORDER BY 之后给出的列的顺序,因此在您的示例中,它按预期工作,因为您的订单是 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您还应该在案例内部切换,以便 'fo' 为 1,'ba' 为 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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