3
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'

谢谢

4

4 回答 4

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
于 2013-04-29T12:07:38.163 回答
1

如果匹配,您可以使用 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
于 2013-04-29T12:05:55.090 回答
1

有一种更简洁的 SQL 类型可以为您提供此答案,但您将每种类型放在不同的行上:

SELECT Type, COUNT(Type) FROM House GROUP BY Type

它的缺点是没有按照您的要求为您提供列;但优点是它适用于任意数量的不同类型,而无需更改查询。

于 2013-04-29T13:07:10.907 回答
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
于 2013-04-29T12:08:01.963 回答