以水平格式显示列

时间:2014-01-06 18:40:05

标签: mysql

我有一张表格如下。

[Date]     [Test_Item]     [Result]

1/2/2014     A                  1.1
2/2/2014     B                  31.1     
3/2/2014     C                  20
5/2/2014     A                  44

我希望以下列格式显示

[Test_Item]     1/2/2014      2/2/2014     3/2/2014   5/2/2014
   A               1.1    
   B                              31.1
   C                                           20
   A                                                       44

我怎样才能做到这一点?在这种情况下请建议查询。

1 个答案:

答案 0 :(得分:2)

这是case声明的基本用法:

select test_item,
       (case when `date` = '1/2/2014' then result end) as `1/2/2014`,
       (case when `date` = '2/2/2014' then result end) as `2/2/2014`,
       (case when `date` = '3/2/2014' then result end) as `3/2/2014`,
       (case when `date` = '5/2/2014' then result end) as `5/2/2014`
from table t;

您没有提及有关类型的任何内容。如果date实际存储为日期或日期/时间(应该是),那么您应该使用ISO标准日期格式进行比较,假设您的格式为d / m / yyyy,则为:

select test_item,
       (case when `date` = '2014-02-01' then result end) as `1/2/2014`,
       (case when `date` = '2014-02-02' then result end) as `2/2/2014`,
       (case when `date` = '2014-02-03' then result end) as `3/2/2014`,
       (case when `date` = '2014-02-05' then result end) as `5/2/2014`
from table t;