有一个这样的行集:

| ID |     OP_CODE | OWNER |  MEASURE | COUNT |
|----|-------------|-------|----------|-------|
|  1 | Operation 1 |     1 | Geometry |    42 |
|  2 | Operation 1 |     1 | Geometry |    48 |
|  3 | Operation 1 |     1 |   Vacuum |    29 |
|  4 | Operation 1 |     1 |  Electro |    14 |
|  5 | Operation 1 |     2 | Geometry |    87 |
|  6 | Operation 1 |     2 | Geometry |   112 |
|  7 | Operation 1 |     2 |   Vacuum |    78 |
|  8 | Operation 1 |     3 |   Vacuum |    56 |
|  9 | Operation 1 |     3 |  Electro |    78 |

我要按所有者对行进行分组,并将其他度量值(列度量值的值)与列计数之和合并/联接到此结果,如下所示:
| OWNER | GEOMETRY_CNT | VACUUM_CNT | ELECTRO_CNT | TOTAL_CNT |
|-------|--------------|------------|-------------|-----------|
|     1 |           90 |         29 |          14 |       133 |
|     2 |          199 |         78 |      (null) |       277 |
|     3 |       (null) |         56 |          78 |       134 |

在这种情况下,几何碳纳米管、真空碳纳米管、电子碳纳米管是第一表中相应值的总和:
所有者几何结构=42+48=90;
所有者真空度=29;
业主电力公司=14;
业主合计=29+14+90=133;
我怎样才能拿到这一排?
SQL Fiddle

最佳答案

试试这个:

SELECT a.OWNER, SUM(IF(a.MEASURE = 'Geometry', a.COUNT, 0)) GEOMETRY_CNT,
       SUM(IF(a.MEASURE = 'Vacuum', a.COUNT, 0)) VACUUM_CNT,
       SUM(IF(a.MEASURE = 'Electro', a.COUNT, 0)) ELECTRO_CNT,
       SUM(a.COUNT) TOTAL_CNT
FROM operations_schedule a
GROUP BY a.OWNER

检查SQL FIDDLE DEMO
输出
| OWNER | GEOMETRY_CNT | VACUUM_CNT | ELECTRO_CNT | TOTAL_CNT |
|-------|--------------|------------|-------------|-----------|
|     1 |           90 |         29 |          14 |       133 |
|     2 |          199 |         78 |           0 |       277 |
|     3 |            0 |         56 |          78 |       134 |

关于mysql - 用sum和join对行进行分组(构建摘要),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20769472/

10-11 01:41