SQL将行转置为列

时间:2010-01-20 05:14:56

标签: sql postgresql pivot pivot-without-aggregate

我有一个有趣的难题,我认为可以用纯粹的SQL解决。我有类似以下的表格:

responses:

user_id | question_id | body
----------------------------
1       | 1           | Yes
2       | 1           | Yes
1       | 2           | Yes
2       | 2           | No
1       | 3           | No
2       | 3           | No


questions:

id | body
-------------------------
1 | Do you like apples?
2 | Do you like oranges?
3 | Do you like carrots?

我希望获得以下输出

user_id | Do you like apples? | Do you like oranges? | Do you like carrots?
---------------------------------------------------------------------------
1       | Yes                 | Yes                  | No
2       | Yes                 | No                   | No

我不知道会有多少问题,而且它们会是动态的,所以我不能只为每个问题编码。我正在使用PostgreSQL,我相信这称为转置,但我似乎无法找到任何说明在SQL中执行此操作的标准方法。我记得在大学期间在我的数据库课上做这个,但它是在MySQL中,老实说我不记得我们是怎么做的。

我假设它将是联接和GROUP BY语句的组合,但我甚至无法弄清楚如何开始。

有人知道怎么做吗?非常感谢!

编辑1:我发现了一些关于使用crosstab的信息,这似乎是我想要的,但我无法理解它。非常感谢链接到更好的文章!

5 个答案:

答案 0 :(得分:48)

使用:

  SELECT r.user_id,
         MAX(CASE WHEN r.question_id = 1 THEN r.body ELSE NULL END) AS "Do you like apples?",
         MAX(CASE WHEN r.question_id = 2 THEN r.body ELSE NULL END) AS "Do you like oranges?",
         MAX(CASE WHEN r.question_id = 3 THEN r.body ELSE NULL END) AS "Do you like carrots?"
    FROM RESPONSES r
    JOIN QUESTIONS q ON q.id = r.question_id
GROUP BY r.user_id

这是一个标准的数据透视查询,因为您将数据从行“旋转”到列数据。

答案 1 :(得分:11)

我实现了一个真正的动态函数来处理这个问题,而无需硬编码任何特定类的答案或使用外部模块/扩展。它还可以完全控制列排序,并支持多个键和类/属性列。

您可以在此处找到它:https://github.com/jumpstarter-io/colpivot

解决此特定问题的示例:

begin;

create temporary table responses (
    user_id integer,
    question_id integer,
    body text
) on commit drop;

create temporary table questions (
    id integer,
    body text
) on commit drop;

insert into responses values (1,1,'Yes'), (2,1,'Yes'), (1,2,'Yes'), (2,2,'No'), (1,3,'No'), (2,3,'No');
insert into questions values (1, 'Do you like apples?'), (2, 'Do you like oranges?'), (3, 'Do you like carrots?');

select colpivot('_output', $$
    select r.user_id, q.body q, r.body a from responses r
        join questions q on q.id = r.question_id
$$, array['user_id'], array['q'], '#.a', null);

select * from _output;

rollback;

输出:

 user_id | 'Do you like apples?' | 'Do you like carrots?' | 'Do you like oranges?' 
---------+-----------------------+------------------------+------------------------
       1 | Yes                   | No                     | Yes
       2 | Yes                   | No                     | No

答案 2 :(得分:6)

您可以使用crosstab函数以这种方式解决此示例

drop table if exists responses;
create table responses (
user_id integer,
question_id integer,
body text
);

drop table if exists questions;
create table questions (
id integer,
body text
);

insert into responses values (1,1,'Yes'), (2,1,'Yes'), (1,2,'Yes'), (2,2,'No'), (1,3,'No'), (2,3,'No');
insert into questions values (1, 'Do you like apples?'), (2, 'Do you like oranges?'), (3, 'Do you like carrots?');

select * from crosstab('select responses.user_id, questions.body, responses.body from responses, questions where questions.id = responses.question_id order by user_id') as ct(userid integer, "Do you like apples?" text, "Do you like oranges?" text, "Do you like carrots?" text);

首先,您必须安装tablefunc扩展名。从9.1版本开始,您可以使用create extension:

来完成
CREATE EXTENSION tablefunc;

答案 3 :(得分:2)

我写了一个函数来生成动态查询。 它为交叉表生成sql并创建一个视图(如果存在则首先将其删除)。 您可以从视图中选择以获得结果。

这是功能:

CREATE OR REPLACE FUNCTION public.c_crosstab (
  eavsql_inarg varchar,
  resview varchar,
  rowid varchar,
  colid varchar,
  val varchar,
  agr varchar
)
RETURNS void AS
$body$
DECLARE
    casesql varchar;
    dynsql varchar;    
    r record;
BEGIN   
 dynsql='';

 for r in 
      select * from pg_views where lower(viewname) = lower(resview)
  loop
      execute 'DROP VIEW ' || resview;
  end loop;   

 casesql='SELECT DISTINCT ' || colid || ' AS v from (' || eavsql_inarg || ') eav ORDER BY ' || colid;
 FOR r IN EXECUTE casesql Loop
    dynsql = dynsql || ', ' || agr || '(CASE WHEN ' || colid || '=''' || r.v || ''' THEN ' || val || ' ELSE NULL END) AS ' || agr || '_' || r.v;
 END LOOP;
 dynsql = 'CREATE VIEW ' || resview || ' AS SELECT ' || rowid || dynsql || ' from (' || eavsql_inarg || ') eav GROUP BY ' || rowid;
 RAISE NOTICE 'dynsql %1', dynsql; 
 EXECUTE dynsql;
END

$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

以下是我如何使用它:

SELECT c_crosstab('query_txt', 'view_name', 'entity_column_name', 'attribute_column_name', 'value_column_name', 'first');

实施例: 拳击你跑:

SELECT c_crosstab('Select * from table', 'ct_view', 'usr_id', 'question_id', 'response_value', 'first');

比:

Select * from ct_view;

答案 4 :(得分:0)

contrib/tablefunc/中有一个例子。