SQL基于三列将两行合二为一

时间:2017-08-24 14:30:54

标签: sql merge

目前我有这个: 目前的情况 enter image description here

正如您所看到的,Id 1和2之间的唯一区别是Sort是diff(Be或Ov)。我目前有四个measurecolumns BAR_fr BAR_to M2_fr M2_to

我想创建8个measurecolumns,差异将是Be和Ov数据 BAR_fr_Be BAR_to_Be M2_fr_Be M2_to_Be

BAR_fr_Ov
BAR_to_Ov
M2_fr_Ov
M2_to_Ov

新情况 enter image description here

我正在尝试将两行合并为一个基于三列的sql 我想,功能一,RegioId,年。我试过Pivot,但我没有得到我想要的结果。任何帮助表示赞赏! :)

2 个答案:

答案 0 :(得分:0)

设置完表格后,可以使用以下方法填充新表:

INSERT INTO
YourNewTable
SELECT
T1.functionid,
T1.regionid,
T1.[year],
T1.BAR_fr,
T1.BAR_to,
T1.M2_fr,
T1.M2_to,
T2.BAR_fr,
T2.BAR_to,
T2.M2_fr,
T2.M2_to
FROM
YourOldTable T1
INNER JOIN
YourOldTable T2
ON
T2.regionid = T1.regionid
AND
T2.functionid = T1.functionid
AND
T2.[year] = T1.[year]
WHERE
T1.Sort = 'Be'
AND
T2.sort = 'Ov'

答案 1 :(得分:0)

在Mysql中:

CREATE TABLE IF NOT EXISTS `table` (
  `id` int(6) unsigned NOT NULL,
  `functionid` INT,
  `regionid` INT,
  `sort`varchar(200),
  `year` INT,
  `BAR_fr` FLOAT,
  `BAR_to` FLOAT,
  `M2_fr` INT,
  `M2_to` INT,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `table` (id, functionid, regionid, sort, year, BAR_fr, BAR_to, M2_fr, M2_to) VALUES
  ('1', '1','1', 'Be',2010,8.0,9.5,1315,2710),
  ('2', '1','1', 'Ov',2010,9.0,10.75,485,1315),
  ('3', '1','2', 'Be',2010,7.25,9.0,1115,3165),
  ('4', '1','2', 'Ov',2010,8.9,10.5,270,1115);


SELECT t1.functionid, t1.regionid, t1.year, t1.BAR_fr BAR_fr_Be, t1.BAR_to BAR_to_Be ,t1.M2_fr, t1.M2_to M2_to_Be, t2.BAR_fr BAR_fr_Ov, t2.BAR_to BAR_to_Ov,t2.M2_fr M2_fr_Ov, t2.M2_to M2_to_Ov
FROM `table` t1
  JOIN `table` t2 ON t1.functionid = t2.functionid AND t1.regionid = t2.regionid
WHERE t1.sort = 'Be' AND t2.sort = 'Ov';