如何从同一列中选择不同的值?

时间:2012-09-28 04:44:58

标签: mysql sql select

我有一个tablecolumn,类型和年龄,但我希望显示在5列中,因为它的条件如下: | TYPE |年龄< 10 | 10&lt; =年龄&lt; 20 |年龄&gt; 20 |

我怎样才能实现这一目标,因为它只有2 column

我尝试使用不同的别名选择相同的表,但是执行时间长了不好。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ...