我有下表:
name category posts
------------------------------
Client A 01 5348
Client A 05 2584
Client B 02 105
Client C 14 10558
Client C 16 511
Client D 01 4863
Client D 01 1823
现在我想选择以下行:
和
此类别为“01”。所以最终所需的输出是:
Client D 01 4863
Client D 01 1823
我想到的问题:
SELECT name, category, posts
FROM exampletable
WHERE (count number of present distinct categories for each name = '1' AND category='01');
问题在于我不知道如何将“将每个名称的当前不同类别的数量”转换为正确的sql代码。有谁可以帮我解决这个问题?
答案 0 :(得分:2)
您可以使用子查询来实现此目的:
Select e.name, e.category, e.posts from exampletable e
where e.name not in
(select e1.name from exampletable e1 where e.name = e1.name and e.category <> e1.category)
and e.category = '01'
说明:子查询将返回与类别没有一对一关系的所有名称,因此可以使用NOT IN
删除它们并进一步过滤使用AND category = '01'
答案 1 :(得分:0)
经过测试和验证。
create table #t (
name varchar(100),
category varchar(2),
posts int
);
insert into #t
select
'Client A', '01', 5348
union all select
'Client A', '05', 2584
union all select
'Client B', '02', 105
union all select
'Client C', '14', 10558
union all select
'Client C', '16', 511
union all select
'Client D', '01', 4863
union all select
'Client D', '01', 1823;
select
name,
category,
posts
from
#t
where name in
(
select
name
from
#t
group by
name
having
1 = count(distinct category)
)
and '01' = category;
输出:
Client D 01 4863
Client D 01 1823