在 sql 表中
我在第一列有 100 个公司名称。在接下来的 20 列中,有 20 个月,例如 2011 年 7 月,.... 2012 年 7 月...(这些月列包含每个公司的数字需求数据)
我只想有 3 列:公司名称、月份、需求。(每个公司名称将重复20次)
我如何使用 sql 代码转换它?
据我所知,MySQL 中没有UNPIVOT
函数,所以你需要这样做UNION ALL
:
MySQL 5.5.32 架构设置:
CREATE TABLE MyTable
(`id` int, `name` varchar(5), `m1` int, `m2` int, `m3` int, `m4` int, `m5` int, `m6` int, `m7` int, `m8` int, `m9` int, `m10` int, `m11` int, `m12` int, `m13` int, `m14` int, `m15` int, `m16` int, `m17` int, `m18` int, `m19` int, `m20` int)
;
INSERT INTO MyTable
(`id`, `name`, `m1`, `m2`, `m3`, `m4`, `m5`, `m6`, `m7`, `m8`, `m9`, `m10`, `m11`, `m12`, `m13`, `m14`, `m15`, `m16`, `m17`, `m18`, `m19`, `m20`)
VALUES
(1, 'name1', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(2, 'name2', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20),
(3, 'name3', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
;
CREATE TABLE Company
( id INT NOT NULL AUTO_INCREMENT, name CHAR(30), PRIMARY KEY (id))
;
CREATE TABLE Demand
(`id` INT NOT NULL AUTO_INCREMENT, `company_id` int, `month` varchar(3), `value` varchar(5), PRIMARY KEY (id))
;
INSERT INTO Company
SELECT id,name FROM Mytable;
INSERT INTO Demand (company_id, month, value)
SELECT id,'m1' as month, m1 as value FROM Mytable
UNION ALL
SELECT id,'m2' as month, m2 as value FROM Mytable
UNION ALL
SELECT id,'m3' as month, m3 as value FROM Mytable
UNION ALL
SELECT id,'m4' as month, m4 as value FROM Mytable
UNION ALL
SELECT id,'m5' as month, m5 as value FROM Mytable
UNION ALL
SELECT id,'m6' as month, m6 as value FROM Mytable
UNION ALL
SELECT id,'m7' as month, m7 as value FROM Mytable
UNION ALL
SELECT id,'m8' as month, m8 as value FROM Mytable
UNION ALL
SELECT id,'m9' as month, m9 as value FROM Mytable
UNION ALL
SELECT id,'m10' as month, m10 as value FROM Mytable
UNION ALL
SELECT id,'m11' as month, m11 as value FROM Mytable
UNION ALL
SELECT id,'m12' as month, m12 as value FROM Mytable
UNION ALL
SELECT id,'m13' as month, m13 as value FROM Mytable
UNION ALL
SELECT id,'m14' as month, m14 as value FROM Mytable
UNION ALL
SELECT id,'m15' as month, m15 as value FROM Mytable
UNION ALL
SELECT id,'m16' as month, m16 as value FROM Mytable
UNION ALL
SELECT id,'m17' as month, m17 as value FROM Mytable
UNION ALL
SELECT id,'m18' as month, m18 as value FROM Mytable
UNION ALL
SELECT id,'m19' as month, m19 as value FROM Mytable
UNION ALL
SELECT id,'m20' as month, m20 as value FROM Mytable
我的建议是规范您的数据库。您应该至少创建 2 个表:
company:
- id
- name
value:
- company_id
- value
- month (numeric)
然后您可以将每个值(在“值”表中)与相应的公司和相应的月份相关联。
使用 unpivot 命令。此示例采用单行并将其转换为两行。
以下示例采用两行并将其转换为四行。
WITH xset
AS (SELECT 'Expedition' ford
, 'Corvette' gm
, DATE '2013-01-01' ford_raise
, DATE '2013-09-03' gm_raise
, 1 seq
FROM DUAL
UNION ALL
SELECT 'Fusion'
, 'Escalate'
, DATE '2010-07-04'
, DATE '2001-12-31'
, 2
FROM DUAL)
SELECT *
FROM xset UNPIVOT ((event_date, model) FOR event IN ((ford_raise, ford) AS 'Ford Raise', (gm_raise, gm) AS 'GM Raise'))