您没有指定您正在使用什么 RDBMS,但您应该能够通过使用CASE
语句实现聚合函数来获得结果。这个过程类似于PIVOT
:
select t2.name,
sum(case when t1.size = 1 and t1.type = 'a' then 1 else 0 end) Size1Type1Count,
sum(case when t1.size = 2 and t1.type = 'a' then 1 else 0 end) Size2Type1Count,
sum(case when t1.size = 1 and t1.type = 'b' then 1 else 0 end) Size1Type2Count,
sum(case when t1.size = 2 and t1.type = 'b' then 1 else 0 end) Size2Type2Count
from table1 t1
inner join table2 t2
on t1.ownerid = t2.id
group by t2.name
请参阅带有演示的 SQL Fiddle
结果:
| NAME | SIZE1TYPE1COUNT | SIZE2TYPE1COUNT | SIZE1TYPE2COUNT | SIZE2TYPE2COUNT |
--------------------------------------------------------------------------------
| A | 1 | 1 | 2 | 0 |
| B | 2 | 0 | 0 | 0 |
如果你想包括你的count
领域,那么你会使用这样的东西:
select t2.name,
sum(case when t1.size = 1 and t1.type = 'a' then "Count" end) Size1Type1Count,
sum(case when t1.size = 2 and t1.type = 'a' then "Count" end) Size2Type1Count,
sum(case when t1.size = 1 and t1.type = 'b' then "Count" end) Size1Type2Count,
sum(case when t1.size = 2 and t1.type = 'b' then "Count" end) Size2Type2Count
from table1 t1
inner join table2 t2
on t1.ownerid = t2.id
group by t2.name;
请参阅带有演示的 SQL Fiddle
结果:
| NAME | SIZE1TYPE1COUNT | SIZE2TYPE1COUNT | SIZE1TYPE2COUNT | SIZE2TYPE2COUNT |
--------------------------------------------------------------------------------
| A | 12 | 12 | 34 | (null) |
| B | 29 | (null) | (null) | (null) |
或者您甚至可以对表执行多个连接以获得您想要的结果:
select t2.name,
sum(t1_a1."count") Size1Type1Count,
sum(t1_a2."count") Size2Type1Count,
sum(t1_b1."count") Size1Type2Count,
sum(t1_b2."count") Size2Type2Count
from table2 t2
left join table1 t1_a1
on t1_a1.ownerid = t2.id
and t1_a1.size = 1
and t1_a1.type = 'a'
left join table1 t1_a2
on t1_a2.ownerid = t2.id
and t1_a2.size = 2
and t1_a2.type = 'a'
left join table1 t1_b1
on t1_b1.ownerid = t2.id
and t1_b1.size = 1
and t1_b1.type = 'b'
left join table1 t1_b2
on t1_b2.ownerid = t2.id
and t1_b2.size = 2
and t1_b2.type = 'b'
group by t2.name
请参阅带有演示的 SQL Fiddle