Oracle SQL,根据来自另一个select

时间:2017-12-11 04:02:20

标签: sql database oracle

我想结合" COUNT(DEPARTMENT_ID)"列基于" LOCATION_ID"与相应的" DEPARTMENT_ID"相同来自另一个选择陈述。我有这个选择语句,它给了我多少次" DEPARTMENT_ID"来了。

select DEPARTMENT_ID, COUNT(DEPARTMENT_ID) FROM EMPLOYEES GROUP BY DEPARTMENT_ID;

输出:

DEPARTMENT_ID COUNT(DEPARTMENT_ID)
------------- --------------------
          100                    6
           30                    6
                                 0
           90                    3
           20                    2
           70                    1
          110                    2
           50                   45
           80                   34
           40                    1
           60                    5

DEPARTMENT_ID COUNT(DEPARTMENT_ID)
------------- --------------------
           10                    1

12 rows selected.

我有另外一个选择告诉我什么" DEPARTMENT_ID"相应的" LOCATION_ID"但我不确定如何结合" COUNT(DEPARTMENT_ID)"基于" LOCATION_ID"是一样的。

select DEPARTMENT_ID, LOCATION_ID from DEPARTMENTS;

输出:

DEPARTMENT_ID LOCATION_ID
------------- -----------
           10        1700
           20        1800
           30        1700
           40        2400
           50        1500
           60        1400
           70        2700
           80        2500
           90        1700
          100        1700
          110        1700

DEPARTMENT_ID LOCATION_ID
------------- -----------
          120        1700
          130        1700
          140        1700
          150        1700
          160        1700
          170        1700
          180        1700
          190        1700
          200        1700
          210        1700
          220        1700

DEPARTMENT_ID LOCATION_ID
------------- -----------
          230        1700
          240        1700
          250        1700
          260        1700
          270        1700

27 rows selected. 

任何想法?

2 个答案:

答案 0 :(得分:1)

更新的代码:

您可以使用内部联接,INNER JOIN关键字选择两个表中具有匹配值的记录。您可以使用以下查询。

 select t1.DEPARTMENT_ID, COUNT(t1.DEPARTMENT_ID) ,t2.LOCATION_ID FROM EMPLOYEES t1 INNER JOIN (select DEPARTMENT_ID, LOCATION_ID from  DEPARTMENTS) t2 
    on t1.DEPARTMENT_ID = t2.DEPARTMENT_ID  GROUP BY t1.DEPARTMENT_ID,t2.LOCATION_ID ;

答案 1 :(得分:1)

如果您的目标是根据其位置简单地计算部门数量,那么下面的查询就足够了。

select LOCATION_ID, count(DEPARTMENT_ID) from DEPARTMENTS group by LOCATION_ID

如果您需要根据您需要使用内部联接和按地点ID分组的位置计算员工数量。

 select t2.LOCATION_ID, COUNT(t1.DEPARTMENT_ID) 
FROM EMPLOYEES t1 INNER JOIN (select DEPARTMENT_ID, LOCATION_ID from  DEPARTMENTS) t2 
 on t1.DEPARTMENT_ID = t2.DEPARTMENT_ID  GROUP BY t2.LOCATION_ID ;