添加新列SQL查询

时间:2014-03-15 18:42:06

标签: sql postgresql

我有一个像

这样的查询
select SUM(*) as "tot1" from table1 t, table2 t2 where t1.id=t2.id and t1.column=1

select SUM(*) as "tot2" from table1 t, table2 t2 where t1.id=t2.id and t1.column=2

select SUM(*) as "tot3" from table1 t, table2 t2 where t1.id=t2.id and t1.column=3

我希望查询结果看起来像这样

 tot1     tot2     tot3

 500       600      3

这甚至可能吗?或者是否有任何替代解决方案让我在同一个表中查看这些查询。

3 个答案:

答案 0 :(得分:2)

试试这个:

select * from 
(select SUM(*) as "tot1" from table1 t, table2 t2 where t1.id=t2.id and t1.column=1) a,

(select SUM(*) as "tot2" from table1 t, table2 t2 where t1.id=t2.id and t1.column=2) b,

(select SUM(*) as "tot3" from table1 t, table2 t2 where t1.id=t2.id and t1.column=3) c

答案 1 :(得分:1)

尝试此查询

select 
    SUM(CASE t1.column WHEN 1 THEN t1.column ELSE 0 END) as tot1, 
    SUM(CASE t1.column WHEN 2 THEN t1.column ELSE 0 END) as tot2, 
    SUM(CASE t1.column WHEN 3 THEN t1.column ELSE 0 END) as tot3 
from 
    table1 t, table2 t2 
where 
    t1.id=t2.id 

答案 2 :(得分:0)

试试这个:

  

选择SUM(t1.column = 1)为“tot1”,SUM(t1.column = 2)为“tot2”,   将SUM(t1.column =)表示为来自table1 t的“tot3”,table2 t2,其中t1.id = t2.id