不同的组以避免重复的部门

zfciruhq  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(243)

我有一张table

Dept    Class
A        x1
A        x2
B        Y1
B        Y2

和表2

Dept    
A   
B

我想加入这两个表和计数组按部门,如果他们是同一个部门(不管类),所以我会有

CountDept  Dept
   1        A
   1        B

目标是避免表1中重复的dept(甚至在表1的同一dept中有多个class)。
我试过了,但没有成功

select distinct count(t1.dept)countdept, t1.dept, t1.class
from table2 t2
join table1 t1 on t2.dept = t1.dept
group by t1.Dept, t1.class
wfauudbj

wfauudbj1#

通过使用partition by可以做到

;WITH tmp AS(
    select distinct  t1.dept, t1.class,
    row_number() over (PARTITION BY t1.dept
    order by t1.class ) as cnt
    from table2 t2
    join table1 t1 on t2.dept = t1.dept  
    )
    select * from tmp where cnt=1
koaltpgm

koaltpgm2#

看起来你根本不想加入。
正如gordon在请求评论中所说,似乎您只想显示table2.dept,每个表的“count”为1,即:

select 1 as count_dept, dept from table2;

如果您只想显示那些也存在于表1中的,那么使用 IN 或者 EXISTS :

select 1 as count_dept, dept from table2 where dept in (select dept from table1);

或者,如果你想“计数”零,那么使用 CASE WHEN :

select 
  case when dept in (select dept from table1) then 1 else 0 end as count_dept,
  dept 
from table2;

相关问题