列Elites.HasInsurance
是:
HasInsurance
true
true
true
我将通过以下命令将此列分组:
Select CASE WHEN e.HasInsurance=1 THEN N'YES' ELSE N'NO' END AS HasInsurance, COUNT(*) as CountHasInsurance
from
Elites e
group by e.HasInsurance
获得的输出等于:
YES ==> 3
但是我想得到以下输出:
YES ==> 3
NO ==> 0
我不想在数据库中创建新表。
答案 0 :(得分:4)
您需要一个LEFT JOIN
。我建议:
select v.hasInsuranceStr, count(e.hasInsurance) as CountHasInsurance
from (values (N'Yes', 'true'), (N'No', 'false')
) v(hasInsuranceStr, hasInsurance) left join
Elites e
on e.hasInsurance = v.hasInsurance
group by v.hasInsuranceStr;
一些注意事项:
hasInsurance
。那已经是一个整数值。我建议使用其他名称。VALUES()
同时具有数字和查找值。true
代表一个字符串,因为SQL Server不支持布尔类型。答案 1 :(得分:3)
这应该给您带来的帮助:
SELECT TF.[value] AS HasInsurance,
COUNT(E.HasInsurance) AS [Count]
FROM (VALUES('True'),('False')) TF([Value])
LEFT JOIN Elites E ON TF.[value] = E.HasInsurance
GROUP BY TF.[value];
查询不会为不存在的数据返回行;因此,VALUES
子句为'True'
和'False'
创建行,这意味着即使值不在Elites
表中也可以返回值。
答案 2 :(得分:1)
您可以使用:
Select
CASE WHEN e.HasInsurance=1 THEN N'YES' ELSE N'NO' END AS HasInsurance,
COUNT(e.HasInsurance) as CountHasInsurance
FROM (SELECT 0 UNION SELECT 1) AS s(x)
LEFT JOIN Elites e
ON s.x = e.HasInsurance
group by s.x