标签:
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
创建表:
DROP TABLE IF EXISTS sales; CREATE TABLE sales( id INT NOT NULL AUTO_INCREMENT, YEAR VARCHAR(4), MONTH VARCHAR(2), amount FLOAT(2,1), PRIMARY KEY(id) ); INSERT INTO sales VALUES (NULL,"1991","1",1.1), (NULL,"1991","2",1.2), (NULL,"1991","3",1.3), (NULL,"1991","4",1.4), (NULL,"1992","1",1.1), (NULL,"1992","2",1.2), (NULL,"1992","3",1.3), (NULL,"1992","4",1.4);
答案:
SELECT sales.year , (SELECT t.amount FROM sales t WHERE t.month=‘1‘ AND t.year= sales.year) ‘1‘, (SELECT t.amount FROM sales t WHERE t.month=‘2‘ AND t.year= sales.year) ‘2‘, (SELECT t.amount FROM sales t WHERE t.month=‘3‘ AND t.year= sales.year) ‘3‘, (SELECT t.amount FROM sales t WHERE t.month=‘4‘ AND t.year= sales.year) AS ‘4‘ FROM sales GROUP BY YEAR;
标签:
原文地址:http://www.cnblogs.com/zhaideyou/p/5932490.html