如何计算每个月而不重复行?

时间:2014-04-24 23:04:10

标签: mysql sql

我试图在查询中创建所有月份,而不是使用多行。

以下是信息:

CREATE TABLE quotes (
  id INT,
  created_at DATE,
  num_policy INT);

INSERT INTO quotes VALUES
 (   1,     '2014-01-01',1234),      
 (   2,     '2014-02-06',5678),  
 (   3,     '2013-04-24',9123), 
 (   4,     '2013-05-24',4567),
 (   5,     '2014-06-20',8912);

我尝试了此查询:http://sqlfiddle.com/#!2/2f4f51/5

SET @year := 2014;

SELECT count(*) AS jan FROM `quotes` WHERE (created_at BETWEEN CONCAT( @year, "-01-01") AND CONCAT( @year, "-01-31")) ;
SELECT count(*) AS feb FROM `quotes` WHERE (created_at BETWEEN CONCAT( @year, "-02-01") AND CONCAT( @year, "-02-29")) ;
......

SELECT count(*) AS dem FROM `quotes` WHERE (created_at BETWEEN CONCAT( @year, "-12-01") AND CONCAT( @year, "-12-31")) ;

我试图在一行中显示所有月份

  |jan|  |feb|  |mar|  |apr| ......
    1       1      0     0

请有人帮助我吗?

我将非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这可以做到这一点:

SELECT CASE WHEN MonthSET @year := 2014;

SELECT SUM(CASE WHEN Month(created_at) = 1 THEN 1 ELSE 0 END) AS jan,
 SUM(CASE WHEN Month(created_at) = 2 THEN 1 ELSE 0 END) AS feb,
 SUM(CASE WHEN Month(created_at) = 3 THEN 1 ELSE 0 END) AS mar,
 SUM(CASE WHEN Month(created_at) = 4 THEN 1 ELSE 0 END) AS apr,
 SUM(CASE WHEN Month(created_at) = 5 THEN 1 ELSE 0 END) AS may,
 SUM(CASE WHEN Month(created_at) = 6 THEN 1 ELSE 0 END) AS jun,
 SUM(CASE WHEN Month(created_at) = 7 THEN 1 ELSE 0 END) AS jul,
 SUM(CASE WHEN Month(created_at) = 8 THEN 1 ELSE 0 END) AS aug,
 SUM(CASE WHEN Month(created_at) = 9 THEN 1 ELSE 0 END) AS sep,
 SUM(CASE WHEN Month(created_at) = 10 THEN 1 ELSE 0 END) AS oct,
 SUM(CASE WHEN Month(created_at) = 11 THEN 1 ELSE 0 END) AS nov,
 SUM(CASE WHEN Month(created_at) = 12 THEN 1 ELSE 0 END) AS `dec`
FROM `quotes` 
WHERE YEAR(created_at) = @year

链接到SQL小提琴: http://sqlfiddle.com/#!2/2f4f51/13/1

答案 1 :(得分:1)

如何使用group by

SELECT month(created_at), count(*) AS cnt
FROM `quotes`
WHERE (created_at BETWEEN CONCAT( @year, "-01-01") AND CONCAT( @year, "-01-31"))
GROUP BY month(created_at)
ORDER BY 1;

这确实会在单独的行上生成值。要将它们放在一行上,请使用条件聚合:

SELECT SUM(month(created_at) = 1) as jan,
       SUM(month(created_at) = 2) as feb,
       . . .
FROM quotes
;WHERE (created_at BETWEEN CONCAT( @year, '-01-01') AND CONCAT( @year, '-01-31'));