我已经尝试过这段代码:
SELECT Count(Gender) As MaleCount, Count(Gender) As FemaleCount
FROM [Session4].[dbo].[Survey]
Where Gender = 'M' or Gender = 'F'
在一次查询中使用两种不同条件进行计数时,无法获得准确的数据。
以下图片:
结果就是这样。
这是原始数据
SELECT TOP (1000) [Departure]
,[Arrival]
,[Age]
,[Gender]
,[CabinType]
,[Q1]
,[Q2]
,[Q3]
,[Q4]
FROM [Session4].[DBO].[Survey]
答案 0 :(得分:6)
COUNT(*)
统计所有行COUNT(column)
计算非空值COUNT(distinct column)
计算不同的非空值COUNT(1)
与COUNT(*)用例/何时+总和:
SELECT
sum(case when Gender = 'M' then 1 else 0 end ) As MaleCount,
sum(case when Gender = 'F' then 1 else 0 end ) As FemaleCount
FROM [Session4].[dbo].[Survey]
会产生这样的事情:
MaleCount | FemaleCount
1000 | 1255
另一种方法是使用简单的goup
SELECT
Gender,
Count(*)
FROM [Session4].[dbo].[Survey]
GROUP BY
Gender
将产生:
Gender | Count
M | 1000
F | 1255
答案 1 :(得分:3)
试试这个:
SELECT sum(case when Gender = 'M' then 1 else 0 end) As MaleCount,
sum(case when Gender = 'F' then 1 else 0 end) As FemaleCount
FROM [Session4].[dbo].[Survey]
如有任何疑问,请与我联系。