2

我有一张表格,列出了人们的名字、年龄和他们最喜欢的颜色。

我需要在 SQL(访问中)中创建一个查询,计算有多少人喜欢红色,有多少人喜欢黄色。

到目前为止,我已经写了这个:

SELECT COUNT (*) as "People who like Yellow or Red"  
FROM Table1  
WHERE Table1.[Favorite Color]='Red'  
OR Table1.[Favorite Color]='Yellow';  

但这会返回喜欢黄色/红色的人的总数(在我的情况下,5)

我有三个喜欢黄色的人,两个喜欢红色的人,我怎样才能独立地显示这些计数?

4

5 回答 5

4

通用解决方案是使用 GROUP BY 运算符。这将根据谁喜欢什么颜色来划分您的数据,然后分别计算每个组。

SELECT
  Table1.[Favorite Color],
  COUNT(*) as "People who like this color"
FROM Table1
GROUP BY Table1.[Favorite Color];

如果您只想在输出中使用 Red 和 Yellow,则可以添加该谓词:

SELECT
  Table1.[Favorite Color],
  COUNT(*) as "People who like this color"
FROM Table1
WHERE Table1.[Favorite Color] IN ('Red','Yellow')
GROUP BY Table1.[Favorite Color];
于 2013-07-16T18:52:17.487 回答
3

您可以使用CASE语句来执行此操作:

SELECT SUM(CASE WHEN [Favorite Color]='Red' THEN 1 ELSE 0 END) as 'People who like Red'
       ,SUM(CASE WHEN [Favorite Color]='Yellow' THEN 1 ELSE 0 END) as 'People who like Yellow'
FROM Table1
于 2013-07-16T18:51:17.497 回答
3
select sum(case when [Favorite Color] = 'Red' then 1 else 0 end) as "People Who Like Red",
       sum(case when [Favorite Color] = 'Yellow' then 1 else 0 end) as "People Who Like Yellow"
from Table1
于 2013-07-16T18:52:05.330 回答
2

你可以试试这个?

SELECT Count(*) AS ["People who like Yellow or Red"], Table1.[Favorite Color]
FROM Table1
GROUP BY Table1.[Favorite Color]
HAVING (((Table1.[Favorite Color])=[Enter Color]));

它将提示用户输入一种颜色,您指定红色或黄色,它会显示查询以计算您单独选择的颜色?

于 2013-07-16T19:05:48.997 回答
1

这是你想要的 ?

select count(*) as "People who like Yellow or Red", Color
form Table1
group by color
于 2013-07-16T18:52:39.217 回答