2012-12-12 54 views
1
Name | Fruit | Red 
John | Apple | Yes 
John | Apple | No 
John | Pear | Yes 
Mike | Mango | No 

算我怎樣才能得到一個結果,看起來像:兩個組由兩列和每個

Name | Fruits total | Red fruits total 
John | 3   | 2 

如何,我可以使用從第一列兩秒操作的另一列的值?可能嗎? 我需要這個查詢ssrs報告,如果這可能有所幫助。

回答

1

您可以使用下面的,如果你是名過濾則可以使用count(*),然後使用聚合函數與CASE確定水果的總數是紅色:

select name, 
    count(*) TotalFruit, 
    sum(case when red='Yes' then 1 else 0 end) TotalRed 
from yourtable 
where name = 'John' 
group by name 

SQL Fiddle with Demo

結果:

| NAME | TOTALFRUIT | TOTALRED | 
-------------------------------- 
| John |   3 |  2 |