2

我有这两个选择,不同之处在于连接表和总和内的情况

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

如何将这些查询合并到一个选择中?问题是我想要所有的'C1'行只有在与table2连接时,与'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
4

3 回答 3

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
于 2013-09-16T15:14:50.023 回答
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;

我会警告您不要进行显式连接。table2中的多个匹配行table3会抛出你的总和。

于 2013-09-16T16:28:46.853 回答
0

我不确定我是否真的理解这个问题,但是呢?

select col1, C1, C2
from table
left join ( ... first query ...) as t1 using(col1)
left join ( ... second query ...) as t2 using(col2)

使用这种技术,您可能可以将子查询转换为连接。

于 2013-09-16T15:18:52.980 回答