将值拆分为其他几列

1tu0hz3e  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(456)

代码:

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小提琴

sigwle7e

sigwle7e1#

您可以通过动态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的优点是,它非常容易出错,并且忘记了代码将捕获的任何新值。不过,要注意团体的限制。
像这样执行动态sql-

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

6psbrbz92#

在这段代码中,您按日期和名称分组,并按升序排序

SELECT * FROM table1
group by day, name
ORDER BY day ASC;

检查图像

des4xlb0

des4xlb03#

您可以使用groupby和groupconcat来执行此操作,如下所示

select t.day,left(t.data,length(t.data)-1)
from
(
SELECT day,replace(group_concat(concat(name,'-')),',','')as data
FROM table1
group by day
  )t

相关问题