【发布时间】:2016-08-24 18:39:24
【问题描述】:
我有一个中型数据库,位于一个星型模式中,有四个星型外部分支。对于我正在评估的一个特定的可视化软件,我需要将此数据库查询到一个 SPSS 文件中,其中一个外部分支以列为轴。我是 PostgreSQL 新手,所以也许我缺少一些简单的方法。
这是一些示例数据(只有 2 个外部分支表 - 态度和人员):
mainTable
id | attitudeKey | response | personKey
1 | 4 | 3 | 2
2 | 1 | 2 | 2
3 | 4 | 1 | 1
4 | 1 | 4 | 1
5 | 5 | 3 | 1
attitudeTable
attitudeKey | attitudeName
4 | happy
1 | quiet
5 | grumpy
personTable
personKey | personName | personAge
1 | Bob | 35
2 | Amy | 30
And here is what the final result of the query needs to look like:
personKey | happy | quiet | grumpy | personName | personAge
1 | 1 | 4 | 3 | Bob | 35
2 | 3 | 2 | | Amy | 30
我确信有一种方法可以从 SQL 中获取此查询,但我只是没有足够的经验来编写连接和数据透视。任何帮助是极大的赞赏。谢谢。
我应该提到,列的顺序在最终结果中并不重要。
现在我只是在 R 中处理数据,但这非常麻烦,我觉得带有交叉表的简单 SQL 查询会让我的生活变得更轻松。
【问题讨论】:
-
postgresql 有一个附加模块,其中包含交叉表函数postgresql.org/docs/9.5/static/tablefunc.html
标签: postgresql pivot spss crosstab star-schema