2

我有一个table2 column,类型和年龄,但我想显示在 5 列中,因为它的条件类似于这个例子:| 类型 | 年龄 < 10 | 10<=年龄<20 | 年龄 > 20 |

我怎么能做到这一点,因为它只有 2 column

我尝试选择具有不同别名的同一张表,但效果不佳,执行时间长。

任何帮助将不胜感激。

4

2 回答 2

3

试试这个:

使用CASE语句

select TYPE,
       case when  Age < 10 then age end as ' Age<10',
       case when  Age between 10 and 20  then age end as ' Age 10-20',
       case when  Age > 20 then age end as ' Age>20'  
from
your_table
于 2012-09-28T04:50:04.813 回答
2

你想要什么作为列值?一个布尔值?

SELECT type, 
  age < 10               AS "Age < 10", 
  age >= 10 AND age < 20 AS "10 <= Age < 20", 
  age > 20               AS "Age > 20" 
FROM table_name;

好的,显然您想要汇总(每个年龄段的人数)

SELECT type,
  (SELECT COUNT(*) FROM table_name AS t2 WHERE age < 10 AND t2.type = type) AS "Age < 10",
  (SELECT COUNT(*) FROM table_name AS t2 WHERE age >= 10 AND age < 20 AND t2.type = type) AS "10 <= Age < 20)"
  ...and so on...
FROM table_name

我想这与您认为太慢的解决方案相同?我想不出另一个更好的了。年龄条件索引会有所帮助,但 MySQL 不支持条件索引。在 PostgreSQL 中你可以CREATE INDEX ON table_name (age) WHERE age < 10 ...

于 2012-09-28T04:56:18.533 回答