MySQL - 从行中创建列

时间:2014-08-25 22:03:24

标签: mysql sql pivot-table

我有一张像这样的树木直径表:

TreeID  Diameter
----------------
1       3
1       2
1       3
2       2
2       2
2       1
1       3

我想按照这样的降序为每棵树增加六个直径:

TreeID  Diameter 1  Diameter 2  Diameter 3  Diameter 4  Diameter 5  Diameter 6
------------------------------------------------------------------------------
1       3           3           3           2
2       2           2           1

我有一个查询来获得直径1到6:

(SELECT Diameter FROM TreeDiameters ORDER BY Diameter DESC LIMIT 1 OFFSET 1) AS Diameter1

但我需要输入一个WHERE子句,以便此子选择中的TreeID与主SELECT中的TreeID匹配。什么是WHERE子句?

2 个答案:

答案 0 :(得分:2)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(measurement_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,TreeID  INT NOT NULL
,Diameter INT NOT NULL
);

INSERT INTO my_table (treeid,diameter) VALUES
(1      , 3),
(1      , 2),
(1      , 3),
(2      , 2),
(2      , 2),
(2      , 1),
(1      , 3);

SELECT x.*
     , COUNT(*) rank
  FROM my_table x
  JOIN my_table y
    ON y.treeid = x.treeid
   AND 
     ( y.diameter > x.diameter
       OR (y.diameter = x.diameter AND y.measurement_id <= x.measurement_id )
     )
  GROUP 
     BY x.treeid, x.diameter, x.measurement_id
-- HAVING rank < something
  ORDER BY treeid,rank;

  +----------------+--------+----------+------+
  | measurement_id | TreeID | Diameter | rank |
  +----------------+--------+----------+------+
  |              1 |      1 |        3 |    1 |
  |              3 |      1 |        3 |    2 |
  |              7 |      1 |        3 |    3 |
  |              2 |      1 |        2 |    4 |
  |              4 |      2 |        2 |    1 |
  |              5 |      2 |        2 |    2 |
  |              6 |      2 |        1 |    3 |
  +----------------+--------+----------+------+

答案 1 :(得分:1)

最简单的方法是将直径放在一个列中,用分隔符分隔。然后,您可以使用group_concat()

SELECT TreeId, substring_index(group_concat(Diameter order by Diameter desc), ',', 6)
FROM TreeDiameters
GROUP BY TreeId
ORDER BY Diameter DESC;

六个实际列需要更多工作。