MySQL"多维?"动态枢轴

时间:2015-08-19 06:05:55

标签: mysql pivot

我承认,我在脑海里。我已经走得太远,以至于我几乎可以在隧道尽头看到光线了,然而,我不确定下一步要采取的措施。

我创建了SQLfiddle example here

这是SQL Pivot:

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(qrv.req_name = ''',qrv.req_name,''', qrv.req_value, NULL)) AS `',qrv.req_name,'`')) INTO @sql
FROM (SELECT qrt.req_name, qrv.id, qrv.req_value FROM qual_requirment_values qrv JOIN qual_requirment_types qrt ON qrt.id = qrv.req_type_id) qrv;

SET @sql = CONCAT('SELECT r.id, r.rank_name, 
                     ', @sql, ' 
                   FROM qual_rank_requirments qrr
                   LEFT JOIN (
                              SELECT qrt.req_name, qrv.id, qrv.req_value 
                                 FROM qual_requirment_values qrv 
                                JOIN qual_requirment_types qrt ON qrt.id = qrv.req_type_id
                             ) AS qrv  ON qrv.id = qrr.req_values_id                   
                   JOIN ranks r ON r.id = qrr.rank_id
                   GROUP BY qrv.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

这是数据结构:

create table qual_rank_requirments
(
  id int,
  rank_id int,
  req_values_id int
);

insert into qual_rank_requirments values
(1, 4, 1),
(2, 4, 2),
(3, 5, 3),
(4, 5, 4),
(5, 6, 3),
(6, 6, 5),
(7, 7, 3),
(8, 7, 6),
(9, 8, 3),
(10, 8, 7);

create table qual_requirment_values
(
  id int,
  req_type_id int,
  req_value int
);

insert into qual_requirment_values values
(1, 1, 55),
(2, 3, 1100),
(3, 1, 110),
(4, 4, 2530),
(5, 5, 4950),
(6, 6, 14630),
(7, 6, 19800);

create table qual_requirment_types
(
  id int,
  req_name varchar(50)
);

insert into qual_requirment_types values
(1, 'pv'),
(2, 'psv'),
(3, 'tv4'),
(4, 'tv5'),
(5, 'tv6'),
(6, 'tv7');

create table ranks
(
  id int,
  rank_name varchar(50)
);

insert into ranks values
(4, 'gyv1'),
(5, 'gyv2'),
(6, 'gyv3'),
(7, 'gyv4'),
(8, 'yns1');

这是我得到的:

id  rank_name   pv      tv4     tv5     tv6     tv7
4   gyv1        55      (null)  (null)  (null)  (null)
4   gyv1        (null)  1100    (null)  (null)  (null)
5   gyv2        110     (null)  (null)  (null)  (null)
5   gyv2        (null)  (null)  2530    (null)  (null)
6   gyv3        (null)  (null)  (null)  4950    (null)
7   gyv4        (null)  (null)  (null)  (null)  14630
8   yns1        (null)  (null)  (null)  (null)  19800

以下是我拍摄的内容:

id  rank_name   pv      tv4     tv5     tv6     tv7
4   gyv1        55      1100    (null)  (null)  (null)
5   gyv2        110     (null)  2530    (null)  (null)
6   gyv3        110     (null)  (null)  4950    (null)
7   gyv4        110     (null)  (null)  (null)  14630
8   yns1        110     (null)  (null)  (null)  19800

我相信以下来源可以帮助我做到这一点。

感谢@strapro的教程:

http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/

特别是@Rockse关于Dynamic Pivots的回答最终导致我参加了@ strapro的教程:

MySQL pivot table

1 个答案:

答案 0 :(得分:1)

您正在对错误的列进行分组,请使用

GROUP BY r.rank_name

FIDDLE