如何根据其他表中的值在运行时添加新列。

时间:2014-02-04 07:13:45

标签: sql select runtime case

我想在select查询中显示新列,其中包含其他表中与id对应的值的总和。 我现在正在学习Sql,所以我只想知道怎么做,我的问题进一步解释为。

I have these two tables joined with t1_id

And result should produce the new column with month sum

1 个答案:

答案 0 :(得分:0)

SELECT table2.t1_id,table1.name,
     sum(case when month='Jan' then amount else 0 end) as jan,
        sum(case when month='feb' then amount else 0 end) as feb,
           sum(case when month='Mar' then amount else 0 end) as Mar
    from table2 inner
    join table1 on table1.t1_id=table2.t1_id group by table2.t1_id,name
    order by table2.t1_id;