在Mysql查询中按Id计算里程碑数

时间:2016-03-09 08:49:53

标签: php mysql

table milestoneevent我有三个表格文件和里程碑事件。我想计算里程碑,但是要按公司计算。

例如,如果我想计算为里程碑id=1添加的最后一个里程碑的数量,我会这样做:

select count('id') as st 
from (
  select idfile,
  max(idmilestone) as max_idmilestone 
  from milestoneevent 
  group by idfile) 
d where max_idmilestone =1

我的问题是如何计算它们但是对于表文件中的每个公司我都有列公司。有关详细信息,请参见图片

1 个答案:

答案 0 :(得分:0)

声明应如下所示

SELECT d.Comp,count(*),d.max_idmilestone FROM (
        SELECT Comp, max(idmilestone) as max_idmilestone, count(idmilestone) as number FROM milestoneevent
        INNER JOIN file ON file.id = idfile
        GROUP BY idfile, Comp
) d GROUP BY d.max_idmilestone, d.Comp

在子查询中,它为每个公司提供max(idmilestone),但仅当idfile存在一个里程碑时,才计算max_idmilestone发生的次数。

我的测试结果是

+-----------+----------+---+
| Comp      | count(*) |   |
+-----------+----------+---+
| Microsoft |        5 | 1 |
| Oracle    |        1 | 1 |
| Microsoft |        2 | 2 |
| Oracle    |        1 | 2 | 
+-----------+----------+---+

**查询公司或里程碑

如果您想查询公司或max_idmilestone,请执行此操作

SELECT d.Comp,count(*),d.max_idmilestone FROM (
        SELECT Comp, max(idmilestone) as max_idmilestone, count(idmilestone) as number FROM milestoneevent
        INNER JOIN file ON file.id = idfile 
        WHERE Comp = "Microsoft"
        GROUP BY idfile, Comp
) d 
WHERE d.max_idmilestone = 1
GROUP BY d.max_idmilestone, d.Comp

<强>输出

+-----------+----------+---+
| Comp      | count(*) |   |
+-----------+----------+---+
| Microsoft |        5 | 1 |
+-----------+----------+---+

对于我的测试我使用了以下结构。跳过了一些测试不必要的列

CREATE TABLE `milestoneevent` (
  `id` INT(22) NOT NULL auto_increment,
  `idfile` INT(64) NOT NULL,
  `idmilestone` INT(64) NOT NULL,
  `company` VARCHAR(64) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `file` (
  `id` int(22) NOT NULL AUTO_INCREMENT,
  `Comp` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

测试数据

+----+--------+-------------+
| id | idfile | idmilestone |
+----+--------+-------------+
|  1 |      1 |           1 |
|  2 |     10 |           1 |
|  3 |     11 |           1 |
|  4 |     12 |           1 |
|  5 |     13 |           1 |
|  6 |     14 |           1 |
|  7 |     15 |           1 |
|  8 |     16 |           2 |
|  9 |     14 |           2 |
| 10 |     18 |           2 |
+----+--------+-------------+


+----+-----------+
| id | Comp      |
+----+-----------+
|  1 | Microsoft |
| 10 | Microsoft |
| 11 | Microsoft |
| 12 | Microsoft |
| 13 | Microsoft |
| 14 | Microsoft |
| 15 | Oracle    |
| 16 | Oracle    |
| 18 | Microsoft |
+----+-----------+