[英]How to find duplicates within a group - SQL 2008
I have a table (MyTable) with following data. 我有一个包含以下数据的表(MyTable)。 (Order by Order_No,Category,Type)
(按Order_No,Category,Type排序)
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
What I need to do is, to scan through the table and see if any 'Category' has more than one 'Main Unit'. 我需要做的是,浏览表,看看是否有任何“类别”具有多个“主机”。 If so, give a warning for the whole Category.
如果是这样,请对整个类别发出警告。 Expected results should look like this.
预期结果应如下所示。
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
I tried couple of ways (using subquery) to achieve results, but no luck. 我尝试了几种方法(使用子查询)来实现结果,但是没有运气。 Please Help !!
请帮忙 !!
(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
One option would be using COUNT() OVER()
to count the main units, partitioning by category; 一种选择是使用
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
do you need to list all records? 您是否需要列出所有记录?
If you only need the duplicates you could do something like this: 如果只需要重复项,则可以执行以下操作:
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;
Another way is to use the CTE. 另一种方法是使用CTE。 Here is the sqlfiddle for this
这是为此的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
just another option, using EXISTS
另一个选择,使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.