gpt4 book ai didi

mysql - 如何将数据集设置为行

转载 作者:行者123 更新时间:2023-11-29 06:41:55 25 4
gpt4 key购买 nike

我的表有以下记录,我需要将以下结果设置到数据表中。

date        code      lc_code      qty
7/1/2018 MC20651 1126 322.00
7/1/2018 MC10102 3356 30.00
7/1/2018 MC10201 4422 56.00
7/1/2018 MC10303 5065 55.00
7/1/2018 MC20902 7012 65.00
7/1/2018 MC50201 1258 45.00
7/1/2018 MC10201 1126 86.00
7/1/2018 MC50201 7012 14.25
7/1/2018 MC20651 1258 322.00
7/1/2018 MC20651 3356 78.00

下面是我需要设置到数据表的内容。您能提供最佳查询吗?

<小时/>
|  Code     |   1126 |   3356 |   4422 |   5065  |   7012 |   1258 |
--------------------------------------------------------------------
| MC20651 | 322.00| 78.00| 0.00 | 0.00 | 0.00 | 322.00 |
--------------------------------------------------------------------
| MC10102 | 0.00 | 30.00 | 0.00 | 0.00 | 0.00 | 0.00 |
--------------------------------------------------------------------
| MC10201 | 86.00| 0.00 | 56.00 | 0.00 | 0.00 | 134.25 |
--------------------------------------------------------------------
| MC10303 | 0.00 | 0.00 | 0.00 | 55.00 | 0.00 | 0.00 |
--------------------------------------------------------------------
| MC20902 | 0.00 | 0.00 | 0.00 | 960.00 | 65.00 | 0.00 |
--------------------------------------------------------------------
| MC50201 | 0.00 | 0.00 | 0.00 | 0.00 | 14.25 | 45.00|
--------------------------------------------------------------------

最佳答案

这可以使用 max(case when ... end) 函数并按 code 分组来实现,这是 T-SQL 中数据透视的常见方法:

示例数据:

create table tbl(date date, code  char(10), lc_code int, qty float);
insert into tbl (code,lc_code,qty) values
('MC20651', 1126, 322.00),
('MC10102', 3356, 30.00),
('MC10201', 4422, 56.00),
('MC10303', 5065, 55.00),
('MC20902', 7012, 65.00),
('MC50201', 1258, 45.00),
('MC10201', 1126, 86.00),
('MC50201', 7012, 14.25),
('MC20651', 1258 , 322.00),
('MC20651', 3356, 78.00);

T-SQL:

select  `code`
`1126`,
`3356`,
`4422`,
`5065`,
`7012`,
`1258`,
`1126` + `3356` + `4422` + `5065` + `7012` + `1258` `sum`
from (
select `code`,
max(case lc_code when 1126 then qty else 0 end) `1126`,
max(case lc_code when 3356 then qty else 0 end) `3356`,
max(case lc_code when 4422 then qty else 0 end) `4422`,
max(case lc_code when 5065 then qty else 0 end) `5065`,
max(case lc_code when 7012 then qty else 0 end) `7012`,
max(case lc_code when 1258 then qty else 0 end) `1258`
from tbl
group by `code`
) `a`;

关于mysql - 如何将数据集设置为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203188/

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