如何在新列中转换(SELECT)不同类型的行?

时间:2014-07-17 16:16:54

标签: mysql sql

我有一个像这样的mysql表:

+------+-------+-------+-------+
| Type | Value | Loc_x | Loc_y |
+------+-------+-------+-------+
|  1   |   30  |   5   |   5   |
|  1   |   40  |   5   |   5   |
|  1   |   50  |   6   |   4   |
|  2   |   25  |   5   |   5   |
|  2   |   20  |   6   |   4   |
+------+-------+-------+-------+

需要创建一个返回类似这样的东西:

+------+-------+-------+-------+-------+-------+
| Type | Value | Type  | Value | Loc_x | Loc_y |
+------+-------+-------+-------+-------+-------+
|  1   |   30  |   2   |   25  |   5   |   5   |
|  1   |   40  |   -   |   -   |   5   |   5   |
|  1   |   50  |   2   |   20  |   6   |   4   |
+------+-------+-------+-------+-------+-------+

算法应该是:
- 当Loc_x和Loc_y相同时,任何类型1行与任何类型2行并排,而仍有行显示。

即当Loc_x和Loc_y相同时,每个不同的类型必须并排。 如果在任何类型上没有相应的值,则应打印 - 。

提前致谢。

修改

用于测试目的的Mysql代码:

CREATE TABLE `sample` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `type` tinyint(3) unsigned NOT NULL,
  `value` int(3) unsigned NOT NULL,
  `loc_x` int(2) unsigned NOT NULL,
  `loc_y` int(2) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

insert  into `sample`(`id`,`type`,`value`,`loc_x`,`loc_y`) values (1,1,30,5,5);
insert  into `sample`(`id`,`type`,`value`,`loc_x`,`loc_y`) values (2,1,40,5,5);
insert  into `sample`(`id`,`type`,`value`,`loc_x`,`loc_y`) values (3,1,50,6,4);
insert  into `sample`(`id`,`type`,`value`,`loc_x`,`loc_y`) values (4,2,25,5,5);
insert  into `sample`(`id`,`type`,`value`,`loc_x`,`loc_y`) values (5,2,20,6,4);

2 个答案:

答案 0 :(得分:1)

这适用于MySQL:

select 
    type1.type,
    type1.value,
    type2.type,
    type2.value,
    type1.Loc_x,
    type1.Loc_y
from 
    (select * , 
            COALESCE((select 0
                      from sample as sample_t
                      where 
                         sample_t.id < sample_a.id 
                           and
                         sample_a.loc_x = sample_t.loc_x
                           and 
                         sample_a.loc_y = sample_t.loc_y
                           and 
                         type = 1
                      limit 1), 1) as is_first 
     from sample as sample_a
     where type = 1) as type1
    left join
    (select *
     from sample
     where type = 2) as type2
    on 
        type1.Loc_x = type2.Loc_x
        and type1.Loc_y = type2.Loc_y
        and type1.is_first = 1

答案 1 :(得分:0)

我不相信您的输出可以有多个同名的列。所以这种方法不会完全产生你的输出。

SELECT sub_type_1.Value as Value_1,
  sub_type_2.Value as Value_2,
  coalesce(sub_type_1.loc_x, sub_type_2.loc_x) as Loc_x
  coalesce(sub_type_1.loc_y, sub_type_2.loc_y) as Loc_y
FROM 
  (SELECT TYPE, Value, Loc_x, Loc_y FROM [Input] WHERE TYPE = 1) sub_type_1
  FULL OUTER JOIN
  (SELECT TYPE, Value, Loc_x, Loc_y FROM [Input] WHERE TYPE = 2) sub_type_2
  ON sub_type_1.Loc_x = sub_type_2.Loc_x
  AND sub_type_1.Loc_y = sub_type_2.Loc_y
相关问题