码迷,mamicode.com
首页 > 其他好文 > 详细

统计每年每月的信息

时间:2016-10-05 17:49:36      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!