Postgresql - 引用其他列的条件语句

时间:2018-03-20 16:54:25

标签: sql postgresql conditional case transpose

我目前有一个如下所示的数据集:

Personid | Question | Response
1        | Name     | Daniel
1        | Gender   | Male
1        | Address  | New York, NY
2        | Name     | Susan
2        | Gender   | Female
2        | Address  | Boston, MA
3        | Name     | Leonard
3        | Gender   | Male
3        | Address  | New York, NY

我还有另一个看起来像这样的表(只是个人ID):

Personid
1
1
1
2
2
2
3
3
3

我想写一个查询来返回这样的内容:

Personid | Name   | Gender | Address
1        |Daniel  | Male   | New York, NY
2        | Susan  | Female | Boston, MA
3        |Leonard | Male   | New York, NY

我认为它是某种" transpose"的组合。 (不确定它是否在SQL中可用)和有关性别的条件声明,但我在获得最终结果时遇到问题。有人可以提供任何建议吗?

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用不同的别名链接到问题表三次。

select
  p.person_id,
  n.response as name,
  g.response as gender,
  a.response as address
from 
  person p
join question n 
    on n.personid = p.personid and n.question = 'Name'
join question g 
    on g.personid = p.personid and g.question = 'Gender'
join question a 
    on a.personid = p.personid and a.question = 'Address'

我假设你的人员表只有3行而不是你列出的9行。如果确实有9个,那么只需选择不同的。

答案 1 :(得分:0)

这是数据透视表的教科书示例。在postgresql中,它由CROSSTAB函数实现,该函数可从TABLEFUNC附加扩展模块获得。

如果您的需求真的像提供的MCVE一样简单,那么多个JOIN可能已经足够了,但在更复杂的情况下CROSSTAB真的是要走的路,值得安装的痛苦一个附加模块,如果您的发行版默认没有安装它。简而言之,如果您的初始表名为dataset,而personidINT

  -- To execute as superuser. Be sure you have installed the extension
  -- package. Execute once to install, it will stay in your database 
  -- ever since.
  CREATE EXTENSION TABLEFUNC;

  -- As normal user
  SELECT * FROM CROSSTAB($$
    SELECT personid, question, response FROM dataset
  $$) AS ct(person INT, name TEXT, gender TEXT, address TEXT);

 person |   name   | gender  |    address    
--------+----------+---------+---------------
      1 |  Daniel  |  Male   |  New York, NY
      2 |  Susan   |  Female |  Boston, MA
      3 |  Leonard |  Male   |  New York, NY
(3 rows)

您可以根据需要在其他表格中添加WHERE条款,JOIN