多个表中的条件和聚合

时间:2016-05-17 05:11:53

标签: mysql conditional case aggregates

我的表格如下所示:

`units`
+----+------+-------+---------------+-------+
| id | tech | jobID |     city      | units |
+----+------+-------+---------------+-------+
|  1 | 1234 | 8535  | San Jose      |     3 |
|  2 | 1234 | 8253  | San Francisco |     4 |
|  3 | 1234 | 2457  | San Francisco |     5 |
|  4 | 1234 | 8351  | Mountain View |     8 |
+----+------+-------+---------------+-------+

以及使用此数据进行某些计算的视图:

`total`
+----+--------+------+-------+
| id |  name  | tech | total |
+----+--------+------+-------+
|  1 | Dan    | 1234 |    12 |
|  2 | Dan SF | 1234 |    12 |
+----+--------+------+-------+ ...

我的问题是,我试图总结Dan在旧金山完成的单位数量以及他在其他地方所做的单位数量(需要专门跟踪在SF中完成的单位数量)。但是,我不确定如何在我的选择查询中执行此操作,如果您查看我当前的总表,您会发现两个总值都只是对所有单位求和而不管城市。

我想得到以下内容:

`total`
+----+--------+------+-------+
| id |  name  | tech | total |
+----+--------+------+-------+
|  1 | Dan    | 1234 |    11 |
|  2 | Dan SF | 1234 |     9 |
+----+--------+------+-------+ ...

我需要帮助编写SELECT,因为我不确定如何使用CASE来获得所需的结果。我尝试过以下方法:

SELECT otherTable.name AS name, units.tech AS tech,
(CASE WHEN City = 'SAN FRANCISCO' THEN SUM(units)
      ELSE SUM(units)
) AS total
FROM units, otherTable
GROUP BY name

但显然这不会起作用,因为我没有区分两个聚合中的城市。

非常感谢任何帮助。

编辑:我当前视图的SELECT查询(带连接信息)如下:

SELECT otherTable.name, units.tech, SUM(units.units)
FROM units
LEFT JOIN otherTable ON otherTable.tech = units.tech
GROUP BY name

对于otherTable,它只是将每个技术ID与名称相关联:

`otherTable`
+----+--------+------+-----------+
| id |  name  | tech | otherInfo |
+----+--------+------+-----------+
|  1 | Dan    | 1234 |    ...... |
+----+--------+------+-----------+

1 个答案:

答案 0 :(得分:1)

首先,您的基本查询似乎是错误的。 unitsotherTable之间的联接没有任何关系,但我不太了解它。

对我来说,您希望将它分成行而不是列,这似乎很奇怪,但您可以执行以下操作:

SELECT otherTable.name AS name, units.tech AS tech,
SUM(units) AS total
FROM units, otherTable
-- not sure if this section should exclude 'SAN FRANCISO' or not
GROUP BY name
UNION ALL
SELECT otherTable.name || ' SF' AS name, units.tech AS tech,
SUM(units) AS total
FROM units, otherTable
WHERE City = 'SAN FRANCISCO'
GROUP BY name

这会给你

+--------+------+-------+
|  name  | tech | total |
+--------+------+-------+
| Dan    | 1234 |    11 |
| Dan SF | 1234 |     9 |
+--------+------+-------+ 

或者如果你想要单独的列,你可以这样做

SELECT otherTable.name AS name, units.tech AS tech,
SUM(units) AS total,
SUM(CASE WHEN City = 'SAN FRANCISCO' THEN units
      ELSE 0
) AS sf_total
FROM units, otherTable
GROUP BY name

这会给你

+--------+------+-------+----------+
|  name  | tech | total | sf_total |
+--------+------+-------+----------+
| Dan    | 1234 |    11 |        9 |
+--------+------+-------+----------+