【问题标题】:MYSQL Pivoting rows to columnMYSQL 将行旋转到列
【发布时间】:2016-06-16 17:17:16
【问题描述】:

我已经创建了下表

CREATE TABLE `demo` (
  `id` int(11) DEFAULT NULL,
  `A1` varchar(56) DEFAULT NULL,
  `B1` varchar(56) DEFAULT NULL,
  `C1` varchar(56) DEFAULT NULL,
  `D1` varchar(56) DEFAULT NULL,
  `E1` varchar(56) DEFAULT NULL,
  `user_id` varchar(56) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我的插入查询

 INSERT INTO `demo` VALUES
(1,'a','b','c','d','d','10');
(2,'a','c','d','a','c','11');
(3,'a','d','d','a','c','12');

然后我的表结构就在这里 My table data

i want output that

为此我尝试了以下

select `10`,`20`,`30` from
(
    (select A1,B1,C1,D1,E1 from demo where id =1) as `10`,
    (select A1,B1,C1,D1,E1 from demo where id =2) as `20`,
    (select A1,B1,C1,D1,E1 from demo where id =3) as `30`
)as s

我收到以下错误

    Error Code: 1064. You have an error in your SQL syntax; check the manual 
    that corresponds to your MySQL server version for the right syntax to use 
near 's' at line 6

请让我知道我做错了什么......或任何其他更好的方法来获得此输出

【问题讨论】:

  • 对不起!这些是什么? one,two,three,four,five
  • 我也不明白你的输出!
  • @SubrataDeyPappu 我已经更新了我的问题。请看看这个
  • @SubrataDeyPappu 我希望 mydata 作为枢轴。你能帮帮我吗
  • 你能发送你的预期结果吗,你的查询完全错误

标签: mysql sql workbench


【解决方案1】:

你似乎想要:

select max(case when id = 1 then val end) as `10`,
       max(case when id = 2 then val end) as `20`,
       max(case when id = 3 then val end) as `30`      
from ((select id, a1 as val, 1 as which from demo) union all
      (select id, b1, 2 as which from demo) union all
      (select id, c1, 3 as which from demo) union all
      (select id, d1, 4 as which from demo) union all
      (select id, e1, 5 as which from demo)
     ) x
group by which;

【讨论】:

  • 只是为了理解他+1!
  • @Gordon Linoff 你能解释一下你的查询和背后的逻辑吗
  • 你为什么在这里使用 1,2,3,4,5。请告诉我你的逻辑
  • @user3172982 。 . .输出有五行,需要聚合和排序。因此需要序号。
  • @GordonLinoff 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多