添加新列SQL查询

时间:2022-06-29 07:44:41

I have a query like

我有一个查询

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

I want a query result look like this

我想查询结果看起来像这样

 tot1     tot2     tot3

 500       600      3

Is this even possible? or is there any alternate solution for me to view these query in same table.

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

3 个解决方案

#1


2  

try this:

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

#2


1  

Try this query

试试这个查询

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 

#3


0  

Try this:

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

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

#1


2  

try this:

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

#2


1  

Try this query

试试这个查询

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 

#3


0  

Try this:

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

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