MySQL:在列值中使用聚合函数

时间:2015-08-12 21:03:45

标签: mysql

给定MySQL模式中的表格,其格式类似于: person_id |创立日期 示例数据:

p1 | 08-12-1995
p2 | 04-11-2002
p3 | 12-31-2007
...

我很难理解语法以执行以下功能: 我想根据他们的创作日期计算人数 例如,我想创建一个GROUPED BY年份的表,并且将有一个支持列,其中包含该年内创建的所有人员的COUNT。 2.使用聚合函数,该函数将能够根据新的GROUPED BY表计算两年值之间的差值 即。

 Year | # of people | Delta
 1995 | 20          | 
 1996 | 22          | +10%
 1997 | 18          | -18%
 ...

我是MySQL的新手,语法仍然让我感到困惑。我不知道基于年份创建新表GROUP'd是否是解决方案的最有效解决方案,我不确定如何将表中的delta计算为我自己的。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效,但要注意不要改变结果列的顺序(它们是非正式的,从左到右评估)。

SET @lastCount := null;
SELECT creationYear AS `Year`
, IF(@lastCount IS NULL
     , ''
     , CONCAT(ROUND(100*((pCount/@lastCount)-1), 0), '%')
  ) AS `Delta`
, @lastCount := pCount AS `# of people`
FROM (
   SELECT YEAR(creation_date) AS creationYear, COUNT(1) AS pCount
   FROM theTable
   GROUP BY creationYear
   ORDER BY creationYear
) AS subQ

答案 1 :(得分:0)

您也可以执行以下操作,但在较大的数据集上,Uueerdo的答案应该更快。

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
( year INT NOT NULL
, person VARCHAR(12) NOT NULL
, PRIMARY KEY(year,person)
);

INSERT INTO my_table VALUES
(1995,'Adam'),
(1995,'Ben'),
(1995,'Charlie'),
(1995,'Dan'),
(1996,'Edward'),
(1996,'Fred'),
(1996,'Gary'),
(1996,'Henry'),
(1997,'Inigo'),
(1997,'James'),
(1997,'Kevin'),
(1997,'Leonard'),
(1998,'Michael'),
(1998,'Noah'),
(1998,'Oliver'),
(1998,'Patrick'),
(1998,'Quentin'),
(1998,'Robert'),
(1999,'Stephen'),
(1999,'Thomas'),
(1999,'Umberto'),
(2000,'Victor'),
(2000,'Walterr'),
(2001,'Xavier'),
(2002,'Yanick'),
(2003,'Zac');

 SELECT a.*  
      , a.n/b.n * 100 pct_diff 
   FROM 
      ( SELECT x.year, COUNT(*) n FROM my_table x GROUP BY year ) a 
   LEFT 
   JOIN 
      ( SELECT x.year, COUNT(*) n FROM my_table x GROUP BY year ) b 
     ON b.year = a.year - 1;
+------+---+----------+
| year | n | pct_diff |
+------+---+----------+
| 1995 | 4 |     NULL |
| 1996 | 4 | 100.0000 |
| 1997 | 4 | 100.0000 |
| 1998 | 6 | 150.0000 |
| 1999 | 3 |  50.0000 |
| 2000 | 2 |  66.6667 |
| 2001 | 1 |  50.0000 |
| 2002 | 1 | 100.0000 |
| 2003 | 1 | 100.0000 |
+------+---+----------+