我的表有下面的记录,而我需要的是下面的结果设置到数据表中。
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
以下是我需要设置为datatable的内容。您能提供最好的查询吗?
| 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|
--------------------------------------------------------------------
答案 0 :(得分:2)
这可以使用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`;