我有这两个选择,差异在连接表和总和
中的情况select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1
from table1
join table2 on table1.col3 = table2.col3
group by table1.col1
select
table1.col1
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table3 on table1.col3 = table3.col3
group by table1.col1
如何将这些查询合并为一个选择?问题是我只想在与table2连接时使用所有'C1'行,与'C2'相同。 这是连接的一个示例,因为您可以看到两个连接中的col3是等效的(就列的类型而言)但不是值
select table1.col1, table1.col2, table2.col3 from table1 join table2 on table1.col3 = table2.col3
table1.col1 | table1.col2 | table2.col3
'COD1' 'C1' 543
'COD1' 'C2' 329
'COD2' 'C2' 123
'COD1' 'C1' 943
select table1.col1, table1.col2, table3.col3 from table1 join table3 on table1.col3 = table3.col3
table1.col1 | table1.col2 | table3.col3
'COD2' 'C2' 632
'COD1' 'C1' 895
'COD1' 'C2' 248
'COD2' 'C1' 458
答案 0 :(得分:2)
如果你想要单列中的所有C1和C2,那么你可以去UNION或UNION ALL(还包括重复项):
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1
from table1
join table2 on table1.col3 = table2.col3
union
select
table1.col1
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table3 on table1.col3 = table3.col3
如果你想在单独的列中使用C1和C2,那么你可以在第一个查询中简单地为C2列添加case语句:
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1,
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table2 on table1.col3 = table2.col3
join table3 on table1.col3 = table3.col3
答案 1 :(得分:0)
我不确定我是否真的理解这个问题,但
呢select col1, C1, C2
from table
left join ( ... first query ...) as t1 using(col1)
left join ( ... second query ...) as t2 using(col2)
使用这种技术,您可以将子查询转换为连接。
答案 2 :(得分:0)
假设您的查询应该有明显的group by
子句,您可以执行以下操作:
select t1.col1,
sum(case when t1.col3 in (select col3 from table2) and
t1.col2 = 'C1'
then t1.value else 0
end) as C1,
sum(case when t1.col3 in (select col3 from table3) and
t1.col2 = 'C2'
then t1.value else 0
end) as C2
from table1 t1
group by t1.col1;
我会提醒你做明确的连接。 <{1}}和table2
中的多个匹配行会甩掉您的总和。