This will list you the (item_id, dep_id) pairs where there are different valud_is's.
select
item_id,
dep_id
from
table
group by
item_id,
dep_id
having
count(distinct value_id)>1
题
I have the following table
item_id dep_id value_id
67 20 3
67 20 2
68 20 8
68 20 8
68 20 8
97 16 3
I need to make sure that the table has the same value_id for each item in each department_id. In other words I must not have an item_id with different value_id for a given department_id.
In the above example the first two rows are invalid because the item 67, in department_id 20 appears with different value_ids (3,2)
Is there a query to perform in order to catch the "anomalies"? I am using SQL Server 2005
Thanks in advance!
解决方案
This will list you the (item_id, dep_id) pairs where there are different valud_is's.
select
item_id,
dep_id
from
table
group by
item_id,
dep_id
having
count(distinct value_id)>1
其他提示
DISTINCT is usually more expensive, this might use less resources (and additionally shows two different values):
select
item_id,
dep_id,
min(value_id),
max(value_id)
from
table
group by
item_id,
dep_id
having
min(value_id) <> max(value_id)