0

帮助!这是我需要完成的一个非常简单的 a、b、c 示例。我一直在拔头发。我以前写过这个,但现在无法理解它!就是这样,实际和预期的结果如下所示:

set nocount on
declare @a table (id int, a varchar(10))
declare @b table (ref int, b varchar(10), c varchar(20))


insert into @a select 1, 'bingo'
insert into @a select 2, 'bongo'


insert into @b select 1, 'T5', 'asdfwef'
insert into @b select 1, 'T8', 'asfqwez'
insert into @b select 1, 'T6', 'qweoae'
insert into @b select 1, 'T8', 'qzoeqe'
insert into @b select 1, 'T9', 'oqeizef'
insert into @b select 2, 'T3', 'awega'
insert into @b select 2, 'T6', 'fhaeaw'
insert into @b select 2, 'T3', 'fqsegw'


select * from @a a join @b b on a.id = b.ref

-- Expected  (Uniqueness is: a’s id to b’s ref and the first b value ingoring b’s c value)
----1,bingo,1,T5,asdfwef
----1,bingo,1,T8,asfqwez
----1,bingo,1,T6,qweoae
----1,bingo,1,T9,oqeizef
----2,bongo,2,T3,awega
----2,bongo,2,T6,fhaeaw

-- Actual
----1,bingo,1,T5,asdfwef
----1,bingo,1,T8,asfqwez
----1,bingo,1,T6,qweoae
----1,bingo,1,T8,qzoeqe
----1,bingo,1,T9,oqeizef
----2,bongo,2,T3,awega
----2,bongo,2,T6,fhaeaw
----2,bongo,2,T3,fqsegw
4

1 回答 1

1

您的查询返回正确的结果。中的所有匹配值@b

如果你想要第一个 b 值,你需要做两件事。首先,您需要在 b 中包含一个排序列,以便您知道“第一”是什么。请记住,SQL 表是无序的。这很简单:

declare @b table (id int identity(1,1) not null, ref int, b varchar(10), c varchar(20));

然后,您必须更改插入以插入除 id 之外的所有内容:

insert into @b(ref, b, c) select 1, 'T5', 'asdfwef';

现在您已准备好进行实际查询:

select *
from @a a join
     (select b.*, row_number() over (partition by b.ref, b.b order by b.id) as seqnum
      from @b b 
     ) b
     on a.id = b.ref and b.seqnum = 1
于 2013-03-29T23:06:21.560 回答