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 报告。

4

1 回答 1

1

您可以使用以下内容,如果您按名称过滤,那么您可以使用count(*)然后使用带有 a 的聚合函数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

结果:

| NAME | TOTALFRUIT | TOTALRED |
--------------------------------
| John |          3 |        2 |
于 2012-12-12T15:02:47.820 回答