2016-05-17 37 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