0

我的表格如下所示:

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

1 回答 1

1

首先,您的基本查询似乎是错误的。units和之间的连接没有任何意义otherTable,但我知道的还不够多。

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

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 |
+--------+------+-------+----------+
于 2016-05-17T05:34:58.403 回答