将一行中的选择列转换为多行

时间:2018-01-26 01:11:46

标签: mysql sql database performance

我花了几个小时修补这个问题无济于事。我有一个包含行的数据集,我希望将特定列子选择到不同的数据集中。

我遇到的问题是将ATBBBOESLK翻译成一个partner按FID和时间分组的列。

我能够自己复制大部分数据集。 AT ...列最初提供为0,1,5或10.我唯一感兴趣的数据是1s和5s,并作为列名转换。初始数据集由此查询生成:

select FID, `time`, 
if((`AT` != 0 and `AT` < 10), "AT", "") as `AT`,
if((`BB` != 0 and `BB` < 10), "BB", "") as `BB`,
if((`BO` != 0 and `BO` < 10), "BO", "") as `BO`,
if((`BT` != 0 and `BT` < 10), "BT", "") as `BT`,
if((`ES` != 0 and `ES` < 10), "ES", "") as `ES`
from f_data group by FID, `time`;

示例输入

`FID`  `time` `AT``BB``BO``ES``LK`
BT201   7:00   AT  BB      ES  LK  
BT201   7:15   AT  BB  BO      LK  
BT201   7:30           BO  ES  LK  
BT201   7:45   AT  BB  BO  ES  LK  
BT201   8:00   AT      BO  ES  LK  

期望输出

`FID`  `time` `partner`
BT201   7:00   AT
BT201   7:00   BB
BT201   7:00   ES
BT201   7:00   LK
BT201   7:15   AT
BT201   7:15   BB
BT201   7:15   BO
BT201   7:15   LK

我已经能够使用plyr通过R生成此输出但是还没有能够在纯MySQL中生成此输出。如果需要,mysql --version输出如下:

Ver 14.14 Distrib 5.5.58, for debian-linux-gnu (x86_64) using readline 6.2

1 个答案:

答案 0 :(得分:0)

select FID, `time`, `AT` as `partner`
from input_table
where `AT` = "AT"

union all

select FID, `time`, `BB` as `partner`
from input_table
where `BB` = "BB"

union all

select FID, `time`, `BO` as `partner`
from input_table
where `BO` = "BO"

union all

select FID, `time`, `ES` as `partner`
from input_table
where `ES` = "ES"

union all

select FID, `time`, `LK` as `partner`
from input_table
where `LK` = "LK"

order by FID, `time`, `partner`