`
hnus
  • 浏览: 27971 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
mysql行列互转问题 mysql, pivot, pivot table basics: rows to columns, rows to colums common mysql quary
--From table tbl( class, member ), you want to cross-tabulate all classes with their members. In SQL terms, you aggregate --members over classes. In MySQL:

SELECT class,GROUP_CONCAT(member)
FROM tbl
GROUP BY class;

--With that simple query, you're halfway toward cross-tabulation, halfway to implementing a simple CUBE, and halfway to --basic entity-attribute-value (EAV) logic. This is easier to see if we have two columns, rather than just one, to --tabulate against the grouping column:

DROP TABLE IF EXISTS tbl;
CREATE TABLE tbl( id INT, colID INT, value CHAR(20) );
INSERT INTO tbl VALUES
  (1,1,'Sampo'),(1,2,'Kallinen'),(1,3,'Office Manager'),
  (2,1,'Jakko'),(2,2,'Salovaara'),(2,3,'Vice President');

--To tabulate all colID and value values against all id values—that is, to write a reporting CUBE for the table—write a --GROUP_CONCAT() instruction for each colID found in the table, then GROUP BY id:

SELECT 
  id, 
  GROUP_CONCAT(if(colID = 1, value, NULL)) AS 'First Name',
  GROUP_CONCAT(if(colID = 2, value, NULL)) AS 'Last Name',
  GROUP_CONCAT(if(colID = 3, value, NULL)) AS 'Job Title'
FROM tbl
GROUP BY id;
-------------------this is the quary reslut----------------------------------
+------+------------+-----------+----------------+
| id   | First Name | Last Name | Title          |
+------+------------+-----------+----------------+
|    1 | Sampo      | Kallinen  | Office Manager |
|    2 | Jakko      | Salovaara | Vice President |
+------+------------+-----------+----------------+ 
--今天突然遇到这个问题,花了一天的时间终于解决,在网上找到的全是sql server 版本的解决办法,需要写存储过程,最后终于在国外一--网站找到mysql语句的写法
--分享一下
Global site tag (gtag.js) - Google Analytics