gpt4 book ai didi

mysql - 将值拆分为其他几列

转载 作者:行者123 更新时间:2023-11-29 07:33:12 25 4
gpt4 key购买 nike

代码:

CREATE TABLE table1 (
day DATE,
name VARCHAR(40)
);
INSERT INTO table1 (day, name)
VALUES
('2018-01-01', 'test1'),
('2018-01-01', 'test2'),
('2018-01-01', 'example'),
('2018-01-01', 'somevalue'),
('2018-01-02', 'test3'),
('2018-01-03', 'test4');

我想将结果拆分成如下内容:

day - name1 - name2 - namex  
DATE - value - value - value

而不是在我选择数据时复制日期。

预期结果:

day - name - name - name - name ...
2018-01-01 - test1 - test2 - example - somevalue
2018-01-02 - NULL - NULL - NULL - NULL - test3

SQL FIDDLE

最佳答案

例如,您可以通过动态 sql 执行此操作,首先找到不同的名称值,然后围绕它们构建其余代码

给予

MariaDB [sandbox]> select * from t;
+------------+-----------+
| day | name |
+------------+-----------+
| 2018-01-01 | test |
| 2018-01-01 | test |
| 2018-01-01 | example |
| 2018-01-01 | somevalue |
| 2018-01-02 | test |
| 2018-01-03 | test |
+------------+-----------+
6 rows in set (0.00 sec)

set @sql = concat('select day, ',
(select group_concat(maxstr)
from
(select concat('max(case when name = ', char(39),name,char(39),' then name else null end) as ', concat('name',@rn:=@rn+1)) maxstr
from
(select distinct name from t) t,(select @rn:=0) rn
) s
)
,
' from t group by day')
;

构建此代码

select day, max(case when name = 'test' then  name else null end) as name1,
max(case when name = 'example' then name else null end) as name2,
max(case when name = 'somevalue' then name else null end) as name3
from t group by day;

运行时产生这个结果

+------------+-------+---------+-----------+
| day | name1 | name2 | name3 |
+------------+-------+---------+-----------+
| 2018-01-01 | test | example | somevalue |
| 2018-01-02 | test | NULL | NULL |
| 2018-01-03 | test | NULL | NULL |
+------------+-------+---------+-----------+
3 rows in set (0.00 sec)

使用动态 sql 的优点是它非常火并且忘记代码将捕获任何新值。不过要注意 group_concat 的限制。

像这样执行动态sql-

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

关于mysql - 将值拆分为其他几列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129207/

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