删除分组依据中的重复值

时间:2017-02-03 14:34:54

标签: sql-server visual-studio-2010 sql-server-2012

我在Microsoft Visual Studio 2010中使用SQL-Server 2012.

作为前言,我无法使用ROW_NUMBER() OVER(PARTITION BY Col),因为我正在使用的Visual Studio版本不支持OVER()方法。不幸的是,我不在一个可以获得新软件的地方。

我有一组部门和工作ID,以便:

SELECT 
   Department, 
   Job_ID
FROM 
   Table1 
JOIN Table2 on 
Table1.id = Table2.id


Department       Job_ID
__________________________

 Marketing         J3
 Engineering       J1
 Marketing         J2
 Recruiting        J2
 Marketing         J8
 Administration    J3
 Recruiting        J1
 Administration    J5
 Administration    J1

我正在尝试按Job_ID进行分组,显示与每个Job_ID关联的不同部门,并​​且仅包含具有2个以上部门的组。最终结果将是:

Department       Job_ID
__________________________

 Administration    J1
 Recruiting        J1
 Engineering       J1
 Marketing         J2
 Recruiting        J2
 Marketing         J3
 Administration    J3

我试过了:

SELECT Job_ID, count(distinct(Department)) as Dept_CountD
FROM Table1 JOIN Table2 on Table1.id=Table2.id
GROUP BY Job_ID
HAVING count(distinct(Department)) >1

但是,它不会将部门与每个ID一起分组。我也知道(并且经过测试)我不能将Department插入Group By语句,因为这会返回不同的部门计数,只等于1!

我已尝试将上述语句构建到CTE并在Job_ID上进行内部联接,因此我只有具有2个以上不同部门的Job_ID,但是,我最终在联接的分组中有重复的部门。

我想或许加入子查询或进行半连接?

3 个答案:

答案 0 :(得分:1)

使用COUNT() Over()窗口聚合

select * from 
(
select count(1)over(partition by Job_ID) as cnt,*
From <<join>>
) A
Where cnt > 1

答案 1 :(得分:1)

这个怎么样:

SELECT 
   Department, 
   Job_ID
FROM Table1 
JOIN Table2 on Table1.id = Table2.id
WHERE Job_ID IN (SELECT Job_ID
                 FROM Table1 JOIN Table2 on Table1.id=Table2.id
                 GROUP BY Job_ID
                 HAVING count(distinct(Department)) >1)

答案 2 :(得分:1)

试试这个:(我只猜测哪个表有Departments,哪个表有Jobs,因为你没有提供架构。

  SELECT Job_ID, count(*) Dept_CountD
  FROM Table1 a JOIN Table2 b on a.id=b.id
  where (Select count(*) from table1
         Where JobId = a.JobId) > 1