从表中选择的记录,所有其他记录具有相同的外键有一定的价值
我有如下表从表中选择的记录,所有其他记录具有相同的外键有一定的价值
ItemStatus
----------
id
item_id
status
我想选择所有ITEM_IDS其中对于利用在该ITEM_ID每个记录状态表A.
例如,如果记录是这样的:
id item_id status
-----------------------
1 1 A
2 1 B
3 2 A
4 2 A
5 3 B
那么唯一ITEM_ID我会回来为2
所
select item_id
from YourTable
group by item_id
having sum(case when status='A' then 1 else 0 end) = count(1)
我其实喜欢这个比我自己的建议更好。看起来它会在大型数据集中表现更好。 Upvoting。 – 2012-01-18 04:27:16
谢谢,还以为他可能接下来想做的事都是B等等。 – JBrooks 2012-01-18 04:33:50
select distinct item_id
from ItemStatus
where status = 'A'
and item_id not in
(
select item_id
from ItemStatus
where status != 'A'
or status is null
)
导致ITEM_IDS的列表中显示为至少一次,从来没有出现别的
像这样的东西应该工作:
SELECT DISTINCT item_id
FROM your_table t1
WHERE
NOT EXISTS (
SELECT *
FROM your_table t2
WHERE t1.item_id = t2.item_id AND t2.status <> 'A'
)
用简单的英语:选择每item_id
其中没有状态不同于'A'的行。
---编辑---
变化的Shark's idea:
SELECT item_id
FROM your_table
GROUP BY item_id
HAVING min(status) = 'A' AND max(status) = 'A'
这有由DBMS被优化相当不错的机会,只要你有{ITEM_ID指数,状态}。下面是SQL Server的执行计划:
OK表示1不会来,因为它有A和B都... 2会因为它有一个只有...吧?? – 2012-01-18 04:21:40
是的,这是正确的 – link664 2012-01-18 04:36:55
okies ..我相信JBrooks解决方案正在... – 2012-01-18 04:44:41