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'
谢谢
您可以使用带有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
如果匹配,您可以使用 acase
并加起来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
有一种更简洁的 SQL 类型可以为您提供此答案,但您将每种类型放在不同的行上:
SELECT Type, COUNT(Type) FROM House GROUP BY Type
它的缺点是没有按照您的要求为您提供列;但优点是它适用于任意数量的不同类型,而无需更改查询。
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