根据列值创建列

时间:2015-01-05 20:11:35

标签: sql postgresql pivot

我不太强烈地使用SQL。我被要求创建一个表格,显示学生在课程管理系统中每个月可以采取的不同课程的能力 所需的结果是输出如下:

month       |  math | english
------------+-------+------------
12/1/2014   | 42    | 137   
1/1/2015    | 137   | 76    
2/1/2015    | 139   | 79    
3/1/2015    | 143   | 83    

"数学"和"英语"是course_kind s,course_kind是表course_capacities上的一列。是否可以根据列中的各种值创建列?

我当前的SQL产生的结果不是最佳结果:

 course_kind |   month    | capacity
-------------+------------+----------
 math         | 2015-01-01 |       47
 math         | 2015-02-01 |       43
 math         | 2015-03-01 |       43
 math         | 2015-04-01 |       45
 math         | 2015-05-01 |       46
 math         | 2015-06-01 |       46
 math         | 2015-07-01 |       46
 math         | 2015-08-01 |       46
 math         | 2015-09-01 |       47
 math         | 2015-10-01 |       47
 math         | 2015-11-01 |       47
 math         | 2015-12-01 |       47
 english      | 2015-01-01 |       97
 english      | 2015-01-01 |       73
 english      | 2015-02-01 |       76
 english      | 2015-03-01 |       79
 english      | 2015-04-01 |       83
 english      | 2015-05-01 |       83
 english      | 2015-06-01 |       87
 english      | 2015-07-01 |       89
 english      | 2015-08-01 |       91
 english      | 2015-09-01 |       93
 english      | 2015-10-01 |       97
 english      | 2015-11-01 |       97
 english      | 2015-12-01 |       97

这是SQL:

SELECT
    course_capacities.course_kind,
    monthly_course_capacities.month,
    monthly_course_capacities.capacity
FROM course_capacities
    INNER JOIN monthly_course_capacities ON course_capacities.id = monthly_course_capacities.course_capacity_id
    ORDER BY course_capacities.course_kind ASC,
    monthly_course_capacities.month ASC;

1 个答案:

答案 0 :(得分:3)

您可以使用case based aggregation,以防run_kind列值已知并且受限制,否则需要创建动态查询。

SELECT
    monthly_course_capacities.month,
    max(case when course_capacities.course_kind ='math' then capacity end ) as math,
    max(case when course_capacities.course_kind ='english' then capacity end ) as english,
FROM course_capacities
INNER JOIN monthly_course_capacities ON course_capacities.id = monthly_course_capacities.course_capacity_id
GROUP BY monthly_course_capacities.month