gpt4 book ai didi

mysql - SQL从值创建列并填充其他列

转载 作者:行者123 更新时间:2023-11-29 03:04:00 25 4
gpt4 key购买 nike

我想从 1 列中获取值,并将它们转换为另一列的标题。它更容易向您展示:

初始表:

Name      | Label   | Value
Tom Jones | January | 42
Rick James| March | 83

结束表:

Name      | January | March
Tom Jones | 42 | NULL
Rick James| NULL | 83

由于我在标签上进行的排序和排序类型,因此需要这样的格式。

更新:当我提到多列值(value)时,我的意思是这样的:

Name      | Label_1   | ValueA_1 | ValueB_1 | Label_2 | ValueA_2 | ValueB_2
Tom Jones | January | 42 | 77 | March | 99 | 22
Rick James| March | 83 | 17 | May | NULL | 112

最佳答案

使用 CREATE TABLE NewTable AS SELECT ...:

CREATE TABLE newTable
SELECT
NAme,
SUM(CASE WHEN Label = 'January' THEN value END) AS January,
SUM(CASE WHEN Label = 'March' THEN value END) AS March
FROM tablename AS t1
GROUP BY Name;

这将创建一个全新的表 newTable,其结构与 SELECT 语句相同。


更新:

根据您的评论,如果您想获取逗号分隔的 value 的值:

CREATE TABLE newTable
SELECT
Name,
GROUP_CONCAT(CASE WHEN Label = 'January' THEN value END) AS January,
GROUP_CONCAT(CASE WHEN Label = 'March' THEN value END) AS March
FROM table1 AS t1
GROUP BY Name;

更新:

如果您想动态执行此操作,而不是对值进行硬编码,则必须使用动态 sql 来执行此操作,如下所示:

SET @sql = NULL;

SELECT
GROUP_CONCAT(DISTINCT CONCAT('GROUP_CONCAT(IF(Label = ''',
Label, ''', value, NULL)) AS ', '''', Label , '''')
) INTO @sql
FROM Table1 ;

SET @sql = CONCAT('CREATE TABLE newTable ',
'SELECT Name,' ,
@sql, ' FROM table1 ',
' GROUP BY Name');


prepare stmt
FROM @sql;

execute stmt;

Updated SQL Fiddle Demo

关于mysql - SQL从值创建列并填充其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18637160/

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