SELECT COUNT(Type) from House where Type = 1
SELECT COUNT(Type) from House where Type = 2
SELECT COUNT(Type) from House where Type = 3
我的问题是:我想加入以上3个语句来获得:3列,例如: ColumnType1:'50',ColumnType2:'60',columnType3:'45'
感谢
答案 0 :(得分:3)
您可以使用带有CASE
表达式的聚合函数创建列:
SELECT
count(case when Type = 1 then Type end) as type_1,
count(case when Type = 2 then Type end) as type_2,
count(case when Type = 3 then Type end) as type_3
from House
答案 1 :(得分:1)
如果case
匹配
Type
并加起来
SELECT sum(case when Type = 1 then 1 else 0 end) as type_1,
sum(case when Type = 2 then 1 else 0 end) as type_2,
sum(case when Type = 3 then 1 else 0 end) as type_3
from House
答案 2 :(得分:1)
有一种更干净的SQL可以为您提供这个答案,但您将在不同的行上使用每种类型:
SELECT Type, COUNT(Type) FROM House GROUP BY Type
它的缺点是没有按照你的要求给你列;但优点是它适用于任何数量的不同类型,而无需更改查询。
答案 3 :(得分:0)
SELECT
COUNT(Type) as val1,
(SELECT COUNT(Type) from House where Type = 2) as val2,
(SELECT COUNT(Type) from House where Type = 3) as val3
from House where Type = 1