统计每年每月的信息
Posted 逸足天涯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了统计每年每月的信息相关的知识,希望对你有一定的参考价值。
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;
以上是关于统计每年每月的信息的主要内容,如果未能解决你的问题,请参考以下文章
Rails:如何构建每天/每月/每年的统计数据或如何缺少与数据库无关的 SQL 函数(例如:STRFTIME、DATE_FORMAT、DATE_TRUNC)