我有一张表格列出了人们的名字,他们的年龄,以及他们最喜欢的颜色。
我需要在SQL(In access)中创建一个查询,计算有多少人喜欢Red,以及有多少人喜欢Yellow。
到目前为止,我已经写过:
SELECT COUNT (*) as "People who like Yellow or Red"
FROM Table1
WHERE Table1.[Favorite Color]='Red'
OR Table1.[Favorite Color]='Yellow';
但是这会返回喜欢黄色/红色(在我的情况下,5)
的人的总计数我有三个喜欢黄色的人,还有两个喜欢红色的人,我怎样才能相互独立地展示这些数量呢?
答案 0 :(得分:4)
通用解决方案使用GROUP BY运算符。这将根据谁喜欢什么颜色对数据进行分区,然后分别对每个组进行计数。
SELECT
Table1.[Favorite Color],
COUNT(*) as "People who like this color"
FROM Table1
GROUP BY Table1.[Favorite Color];
如果您只想在输出中使用红色和黄色,则可以添加该谓词:
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];
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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]));
它会提示用户输入您指定红色或黄色的颜色,它会显示查询以计算您单独选择的颜色吗?
答案 4 :(得分:1)
这是你在找什么?
select count(*) as "People who like Yellow or Red", Color
form Table1
group by color