2012-03-15 64 views
3

我對SQL很陌生,並且試圖做一些事情而不是愚蠢的方式。爲了給出一些背景,我正在比較運營商分支機構的規劃和實際使用情況,並且需要統計兩者的發生情況。我有一個with subquery as返回類似以下在sql中加入計數

PLANNED | REALIZED 
---------+---------- 
TRUCK | BI-TREM 
TRUCK | TRUCK 
TRUCK | TRUCK 
TRUCK | TRUCK 
TRUCK | TRUCK 
CARRETA | CARRETA 
CARRETA | CARRETA 
TRUCK | KOMBI 
TRUCK | BI-TREM 
CARRETA | KOMBI 
CARRETA | KOMBI 
TRUCK | TRUCK 
CARRETA | CARRETA 
CARRETA | BI-TREM 
CARRETA | CARRETA 
CARRETA | CARRETA 
TRUCK | BI-TREM 

,想返回類似以下

VEHICLE | TOTAL_PLANNED | TOTAL_REALIZED 
--------+---------------+--------------- 
CARRETA | 8    | 5 
TRUCK | 9    | 5 
BI-TREM | 0    | 4 
KOMBI | 0    | 3 

我已經試過以下

select PLANNED, 
     count(*) as TOTAL_PLANNED 
     null as REALIZED, 
     0 as TOTAL_REALIZED 
from subquery 
group by PLANNED 

union all 

select null as PLANNED, 
     0 as TOTAL_PLANNED, 
     REALIZED, 
     count(*) as TOTAL_REALIZED 
from subquery 
group by REALIZED 

返回

CARRETA 8 NULL 0 
TRUCK 9 NULL 0 
NULL 0 BI-TREM 4 
NULL 0 CARRETA 5 
NULL 0 TRUCK 5 
NULL 0 KOMBI 3 

我也嘗試了使用子查詢的所有可用連接,但沒有成功。事實上,RIGHT JOIN的作品,但只是因爲所有計劃的車輛也在實現方面:如果有一些沒有,我會在VEHICLE列有一個NULL。

感謝您的幫助,即使只是一個指向SQL命令的指針。

PS:這個查詢必須同時在SQL Server和Oracle上工作,所以我在努力爭取純SQL。

回答

7

嘗試:

SELECT PLANNED_REALIZED AS VEHICLE, 
     SUM(TOTAL_PLANNED) AS TOTAL_PLANNED, 
     SUM(TOTAL_REALIZED) AS TOTAL_REALIZED 
FROM 
(select PLANNED AS PLANNED_REALIZED, 
     1 as TOTAL_PLANNED 
     0 as TOTAL_REALIZED 
from subquery 
union all 
select REALIZED as PLANNED_REALIZED, 
     0 as TOTAL_PLANNED, 
     1 as TOTAL_REALIZED 
from subquery 
) SQ 
GROUP BY PLANNED_REALIZED 
+0

這一工程!這似乎有點複雜,我選擇答案是因爲更多的人喜歡它。這需要一些時間來理解這兩個答案...... – 2012-03-15 16:17:33

+1

它可能*看起來*更復雜,但它只需要兩次讀取表格,而不是2次(n + 1)讀取Simon解決方案所需的讀數。 – 2012-03-15 16:52:28

1

我認爲這應該工作:

select T.VEHICLE, 
     (SELECT count(*) FROM Table AS T1 WHERE T1.PLANNED = T.VEHICLE) AS TOTAL_PLANNED 
     (SELECT count(*) FROM Table AS T2 WHERE T2.REALIZED = T.VEHICLE) AS TOTAL_REALIZED, 
from (SELECT DISTINCT PLANNED AS VEHICLE FROM Table 
     UNION SELECT DISTINCT REALIZED AS VEHICLE FROM Table) AS T 
+0

謝謝,這也適用!儘管如此,我不得不花費一些時間來了解如何使用'group by':) – 2012-03-15 16:14:30