跨多个表的条件和聚合

Conditionals and Aggregates across Multiple Tables

我有 table 如下所示:

`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 完成的单元数量)。但是,我不确定如何在我的 select 查询中执行此操作,如果您查看我当前的总计 table,您会发现两个总计值只是对所有单位求和,而不管城市。

我想获得以下信息:

`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 |    ...... |
+----+--------+------+-----------+

首先,您的基本查询似乎有误。 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 |
+--------+------+-------+----------+