0

我对这个 sql 查询有很大的问题。根据我的表格,我需要一些类似这样的结果:

table1

Id | Type | Size |Count | OwnerId
___________________________________
1     A      1      12      1
2     A      2      12      1
3     B      1      14      1
4     B      1      20      1
5     A      1      12      2
6     A      1      17      2

表2

Id | name
_________
1     A
2     B

结果

______________________
Name |  Size1Type1 Count |  Size2Type1 Count |  Size1Type2 Count

非常感谢。

4

2 回答 2

2

您没有指定您正在使用什么 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

于 2012-12-01T12:35:50.053 回答
0
SELECT Name, Type, Size, SUM(Count) AS 'Count' FROM Table1, Table2
WHERE Table1.OwnerID = Tabel2.Id
GROUP BY Name, Type, Size
于 2012-12-01T12:40:01.247 回答