gpt4 book ai didi

mysql - 将一行中的选定列转换为多行

转载 作者:行者123 更新时间:2023-11-29 17:59:59 34 4
gpt4 key购买 nike

我花了几个小时解决这个问题,但没有成功。我有一个数据集,其中的行我想将其中的特定列子选择到不同的数据集中。

我遇到的问题是翻译 ATBBBOESLK 到单个合作伙伴 列中,同时按 FID 和时间分组。

我已经能够自己重现该数据集的大部分内容。 AT... 列最初提供为 0、1、5 或 10。我唯一感兴趣的数据是 1 和 5,并强制转换为列名称。初始数据集由以下查询生成:

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 输出如下:

版本 14.14 Distrib 5.5.58,适用于使用 readline 6.2 的 debian-linux-gnu (x86_64)

最佳答案

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`

关于mysql - 将一行中的选定列转换为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48454469/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com