Sql由多个Where条件计数

时间:2012-12-01 12:31:56

标签: sql

我对这个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

非常感谢。

2 个答案:

答案 0 :(得分: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 with Demo

结果:

| 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 with Demo

结果:

| 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 with Demo

答案 1 :(得分:0)

SELECT Name, Type, Size, SUM(Count) AS 'Count' FROM Table1, Table2
WHERE Table1.OwnerID = Tabel2.Id
GROUP BY Name, Type, Size