查询结果将行显示为列
我有一个动态创建复选框的表单。用户登录并在所有复选框中选择 0。复选框数组是从表“选项”生成的。该表单将记录提交到 2 个表“调查”(一条人员数据记录)和“选择”(调查键和选项键(或多个键))中。 我想拿出一份报告,将所有可能的选项显示为列标题,并列出调查表中选择该选项的人员列表。所以我的结果看起来像这样:
FirstAid Triage Firefighting HamRadio
Sam Sue Sam
Judy Judy Bill
Bob
所以所有选项都会显示在结果上,即使没有人选择它。
表的结构是:
OPTIONS
option_id description
SURVEY
survey_id name
SELECTED OPTIONS
survey_id option_id
这是实际数据的简化示例,但包括关键部分(我认为)。如何使用 SQL 来获得我需要的结果?
谢谢
I have a form that dynamically creates checkboxes. The user signs in and selects 0 to all the checkboxes. The checkbox array is generated from the table 'options'. The form submit records into 2 tables 'survey' (one record of person data) and 'selections' (the survey key and the options key (or keys)).
I want to pull out a report that will show all of the possible options as column headings with a list of people from the survey table who selected that option. So my result would look like this:
FirstAid Triage Firefighting HamRadio
Sam Sue Sam
Judy Judy Bill
Bob
So all of the options show on the results, even if no one has selected it.
Structure of the tables are:
OPTIONS
option_id description
SURVEY
survey_id name
SELECTED OPTIONS
survey_id option_id
This is a simplified example of the actual data, but includes the critical pieces (I think). How can I use SQL to get the results I need?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
免责声明:我已经好几年没有使用 Postgres 了,所以可能有比我列出的方法更好的方法来完成这项任务。
选项 1: 使用
Case
When
语句,如下面链接的解决方案中所做的那样。在以下位置创建数据透视表的正确方法postgresql 使用 CASE WHEN
选项 2: 使用
tablefunc contrib
中提供的Crosstab
函数,如下面的链接所示解决方案。PostgreSQL 交叉表查询
crosstab tablefunc contrib
的文档 http://www.postgresql.org/docs/9.1/static/tablefunc.html" postgresql.org/docs/9.1/static/tablefunc.htmlDisclaimer: I have not used Postgres in several years so there may be better methods of accomplishing this task than the ones that I list.
Option 1: Use
Case
When
statements as was done in the below linked solution.correct way to create a pivot table in postgresql using CASE WHEN
Option 2: Use the
Crosstab
function available in thetablefunc contrib
as was done in the below linked solution.PostgreSQL Crosstab Query
Documentation for
crosstab tablefunc contrib
http://www.postgresql.org/docs/9.1/static/tablefunc.html