2016-05-17 72 views
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 | 
+----+--------+------+-------+ ... 

我需要帮助写我的选择,因为我不能确定如何使用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查询(与加盟信息)如下:

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

在你查询你是交叉连接两个表,所以每名与各单位结合。但在您的视图样本中,您向其他人展示了'旧金山'和'丹'的用户'Dan SF'。那个怎么样?请说明两个表格是如何相关的。你怎么知道丹是谁完成了单位? –

+0

对不起,我已经使用加入信息更新了我的帖子。 – mathmorales

+0

好的,这个名字叫'Dan SF'。使用pgreen2的'UNION ALL'查询,然后调整连接。 –

回答

1

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

至于otherTable,它只是每个高科技ID与一个名字相关联首先,看起来您的基本查询是错误的。 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 | 
+--------+------+-------+----------+ 
+0

在我匆忙中,我忘记了加入信息。然而,这正是我所需要的,因为我不确定如何在这种情况下使用CASE,这就足够了。非常感谢你! – mathmorales