排序列独立,使得所有的空值是每列最后(Sort columns independently, suc

2019-10-21 13:11发布

这里被称为示例表animal

name | color
------------
fox  | brown
fox  | red
dog  | gold

现在,我想是这样的结果:

fox   | dog
-------------
brown | gold
red   | 

名称应与不同的颜色值作为行的结果列。

我首先想到的是这样的:

SELECT color
FROM animal
WHERE name='fox'

[some sort of join?]

SELECT color 
FROM animal
WHERE name='dog'

但我不知道什么样的加入会做的伎俩。

第二个想法:

SELECT CASE WHEN name = 'fox' THEN color ELSE NULL END AS fox,
CASE WHEN name = 'dog' THEN color ELSE NULL END AS dog
FROM animal

这将返回:

fox   | dog
-----------
red   | 
brown |
      | gold

我想在此表中移动空值​​到底。 我试过了:

ORDER BY CASE name
        WHEN 'fox' THEN fox
        WHEN 'dog' THEN dog
    END

但我不知道如果这是真的是我想和Postgres唠叨那个狐狸精是不是列,虽然我可以做ORDER BY fox

也许我的做法是总废话或者有某种神奇的聚结,可以做的伎俩?

Answer 1:

你似乎是的印象是,将有一个表中的“自然”顺序(如在电子表格),但是没有。 如果没有ORDER BY这往往恰好是相同的输入顺序为尚未更新,但小表) - ,行以任意顺序返回。

WITH cte AS (
   SELECT row_number() OVER (PARTITION BY name ORDER BY color) AS rn, * 
   FROM   animal
   )
SELECT f.color AS fox, d.color AS dog
FROM        (SELECT rn, color FROM cte WHERE name = 'fox') f
FULL   JOIN (SELECT rn, color FROM cte WHERE name = 'dog') d USING (rn)
ORDER  BY rn;

要点

  • 连接每个颜色序列号用于在每个单独类型的动物CTE 。
  • FULL [OUTER] JOIN是至关重要的,因为行数为狐狸和狗不同。
  • 颜色是按字母顺序排序,NULL值最后自动的,因为它们是在表的通过结束填补缺失行FULL [OUTER] JOIN
  • 这仅扫描一次表。

解释你得到的错误消息(“狐狸”是不是列 ):

  • PostgreSQL的当数条件
  • GROUP BY + CASE语句


Answer 2:

尝试是这样的:

WITH fox_color as 
(SELECT color as fox, row_number() rn
 FROM animal
 WHERE name='fox'),
dog_color as 
(SELECT color as dog, row_number() rn
 FROM animal
 WHERE name='dog')
SELECT fox, dog
FROM fox_color 
JOIN dog_color ON fox_color.rn = dog_color.rn


文章来源: Sort columns independently, such that all nulls are last per column