将最大值从组附加到每行结果?

时间:2015-12-18 10:41:06

标签: mysql sql select group-by greatest-n-per-group

我有类似于以下数据库结构: ApplicationService表:

+-----+--------------+----------+---------------+
|  id | name         | status   | application_id
|  1  | Service 1    |  1       |     24
|  2  | Service 2    |  2       |     24
|  3  | Service 3    |  3       |     25
+-----+--------------+----------+----------------

还有其他表格具有状态定义: CustomerStatus

+------------+--------------+----------+-----------+
|  status_id | name         | level    | is_closed
|  1         | Status 1     |  2       |     1
|  2         | Status 2     |  1       |     0
|  3         | Status 3     |  3       |     1     
+------------+--------------+----------+----------

ApplicationServices的每一行的状态计算为按application_id分组的记录中的最大级别状态。

因此,从ApplicationServices获取包含状态的所有记录将导致类似这样的内容:

+-----+--------------+----------+----------------+-------------+-----------
|  id | name         | status   | application_id | status_name | is_closed
|  1  | Service 1    |  1       |     24         |  Status 1   |    1
|  2  | Service 2    |  2       |     24         |  Status 1   |    1
|  3  | Service 3    |  3       |     25         |  Status 3   |    1
+-----+--------------+----------+----------------+-------------+-----------

是否有一种有效的方法将结果与按application_id分组的max(级别)附加到结果集的每一行?

2 个答案:

答案 0 :(得分:1)

试试这个:

Y

答案 1 :(得分:0)

See working SQLfiddle here

您可能必须执行子查询。子查询只是将两个表连接在一起,按application_id分组/折叠,然后获取最大is_closed值:

SELECT
     t1.status AS `status`,
     t1.application_id AS `app_id`,
     MAX(t2.is_closed) AS `max_is_closed`
   FROM applicationstatus AS t1
  LEFT JOIN customerstatus AS t2 ON
    t1.status = t2.status_id
  GROUP BY t1.application_id

当您合并子查询时,is_closed别名可以访问最大max_is_closed值:

SELECT
  t1.id AS id,
  t1.name AS name,
  t1.status AS `status`,
  t1.application_id AS application_id,
  t2.name AS status_name,
  t3.max_is_closed
FROM applicationstatus AS t1
LEFT JOIN customerstatus AS t2 ON
  t1.status = t2.status_id
LEFT JOIN
  (SELECT
     t1.status AS `status`,
     t1.application_id AS `app_id`,
     MAX(t2.is_closed) AS `max_is_closed`
   FROM applicationstatus AS t1
  LEFT JOIN customerstatus AS t2 ON
    t1.status = t2.status_id
  GROUP BY t1.application_id) AS t3 ON
  t1.application_id = t3.app_id

查询的输出:

enter image description here