具有多列和星期几的PostgreSQL交叉表查询

时间:2018-09-26 18:53:32

标签: postgresql pivot grouping pivot-table crosstab

我正在尝试通过将几列分组来创建数据透视表:用户ID,名称,星期编号和日期名称。 当前的请求没有给出期望的结果。 我需要帮助。

这是我的桌子:

user_id name    week_number day_name    price
2       Luc     8           Sunday      10
2       Luc     8           Monday      15
2       Luc     8           Tuesday     8
2       Luc     8           Wednesday   2
2       Luc     8           Thursday    9
2       Luc     8           Friday      9
2       Luc     8           Saturday    11
2       Luc     9           Saturday    1
2       Luc     9           Friday      13
3       Mathieu 8           Sunday      22
3       Mathieu 8           Monday      13
3       Mathieu 8           Tuesday     9
3       Mathieu 8           Wednesday   3

这是我当前的请求:

SELECT *
FROM   crosstab(
'SELECT user_id, name, week_number,day_name,price
FROM   table_1
ORDER  BY 1,2,3,4' 
) AS ct (
"user_id" integer,
"day_name" text,
"Sunday" integer,   
"Monday" integer,   
"Tuesday" integer,  
"Wednesday" integer,    
"Thursday" integer, 
"Friday" integer,   
"Saturday" integer
);

这是我想要获得的结果。

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以只使用条件聚合:

SELECT user_id, name, week_number
       MAX(price) FILTER (WHERE day_name = 'Sunday') as Sunday,
       MAX(price) FILTER (WHERE day_name = 'Monday') as Monday,
       MAX(price) FILTER (WHERE day_name = 'Tuesday') as Tuesday,
       MAX(price) FILTER (WHERE day_name = 'Wednesday') as Wednesday,
       MAX(price) FILTER (WHERE day_name = 'Thursday') as Thursday,
       MAX(price) FILTER (WHERE day_name = 'Friday') as Friday,
       MAX(price) FILTER (WHERE day_name = 'Saturday') as Saturday
FROM table_1
GROUP BY user_id, name, week_number
ORDER BY user_id, name, week_number;

编辑:

您可以编写没有FILTER的相同逻辑:

       MAX(CASE WHEN day_name = 'Sunday' THEN price END) as Sunday,