在sql中加入计数

时间:2012-03-15 14:53:04

标签: sql join union

我对SQL很陌生,我正在尝试做一些不是愚蠢的事情。为了给出一些背景信息,我正在比较运营商分支中车辆的规划和实现用途,并且需要计算两者的出现次数。我有一个with subquery as返回类似下面的内容

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。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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