如何在组中查找重复项 - SQL 2008

时间:2013-12-27 23:54:38

标签: sql database sql-server-2008

我有一个包含以下数据的表(MyTable)。 (按订单排序,类别,类型)

Order _No   Category    Type    
Ord1    A   Main Unit   
Ord1    A   Other   
Ord1    A   Other   
Ord2    B   Main Unit   
Ord2    B   Main Unit   
Ord2    B   Other   

我需要做的是,扫描表格,看看是否有任何“类别”有多个“主单位”。 如果是这样,请对整个类别发出警告。预期结果应如下所示。

Order _No   Category    Type      Warning
Ord1    A   Main Unit   
Ord1    A   Other   
Ord1    A   Other   
Ord2    B   Main Unit     More than one Main Units
Ord2    B   Main Unit     More than one Main Units
Ord2    B   Other     More than one Main Units

我尝试了几种方法(使用子查询)来获得结果,但没有运气。请帮助!!

(Case
 When (Select t1.Category
             From MyTable as t1 
    Where  MyTable.Order_No = t1.Order_No
                    AND MyTable.Category = t1. Category
        AND  MyTable.Type = t1.Type
               AND  MyTable.Type = ‘Main Unit’
    Group by t1. t1.Order_No, t1. Category, t1.Type
Having  Count(*) >1) = 1
Then ‘More than one Main Units’
Else ‘’ End ) as Warning

4 个答案:

答案 0 :(得分:2)

一种选择是使用COUNT() OVER()计算主要单位,按类别划分;

SELECT Order_No, Category, Type, 
  CASE WHEN COUNT(CASE WHEN Type='Main Unit' THEN 1 ELSE NULL END) 
            OVER (PARTITION BY Category) > 1 
       THEN 'More than one Main Units' ELSE '' END Warning
FROM MyTable

An SQLfiddle to test with

答案 1 :(得分:0)

你需要列出所有记录吗?

如果您只需要重复项,则可以执行以下操作:

select Order_No, Category, Type, count(*) as dupes
from MyTable
where Type='Main Unit'
group by Order_No, Category, Type
having count(*)>1
order by count(*) DESC;

答案 2 :(得分:0)

另一种方法是使用CTE。这是

sqlfiddle
   ;with categoriesWithMoreThanOneType as
   (
      select category, order_type
      from
        mytable
      where 
        order_type = 'Main Unit'
      group by category, order_type
      having count(1) > 1
   )

   select
     m.*, 
     case 
       when c.order_type is null then ''
       else
        'More than one ' + c.order_type 
     end as Warning
   from 
      mytable m 
      left outer join categoriesWithMoreThanOneType c on 
         m.category = c.category

答案 3 :(得分:0)

使用EXISTS

的另一种选择
select [Order], _No, Category, Type, 
    (case when exists (
        select 1 from mytable t2
        Where category = 'main unit'
        and t2.[Order] = t.[Order] and t2._No = t._No
        group by [Order]
        having Count(*) > 1)
     then 'More than one Main Units'
     else '' end) as Warning
From MyTable t

enter image description here