Reputation: 65
I have a table (MyTable) with following data. (Order by 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
Upvotes: 1
Views: 68
Reputation: 4262
just another option, using 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
Upvotes: 0
Reputation:
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;
Upvotes: 0
Reputation: 1150
Another way is to use the CTE. Here is the sqlfiddle for this
;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
Upvotes: 0
Reputation: 180927
One option would be using COUNT() OVER()
to count the main units, partitioning by category;
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
Upvotes: 2