2016-03-21 75 views
0

下面的情況下,這是簡單的數據組,但加入/分組選擇重複數據....加入表具有唯一值

CREATE TABLE #t1 (UnID bigint IDENTITY(1,1), name varchar(5), id bigint) 
insert into #t1 (name,id)values('a',1) 
insert into #t1 (name,id)values('a',2) 
insert into #t1 (name,id)values('a',3) 
insert into #t1 (name,id)values('a',4) 
insert into #t1 (name,id)values('b',5) 
insert into #t1 (name,id)values('c',6) 

CREATE TABLE #t2 (name varchar(5), id bigint) 
insert into #t2 (name,id)values('a',1) 
insert into #t2 (name,id)values('a',2) 
insert into #t2 (name,id)values('a',3) 
insert into #t2 (name,id)values('b',4) 
insert into #t2 (name,id)values('c',5) 

select 
a.UnID, a.name as aName, a.Id as aId, b.Id as bId 
into #t3 
from #t1 a 
join #t2 b on a.name = b.name 

select max(bid),unid from #t3 
group by UnId 

分類結果

bid unid 
3 1 
3 2 
3 3 
3 4 
4 5 
5 6 

分組所需結果

bid unid 
1 1 
2 2 
3 3 
NULL 4 
4 5 
5 6 

,如果沒有找到出價則空

+0

我試圖在兩張桌子上加入,並且希望每次都選擇下一場比賽。如果您認爲有另一種方法可以做到這一點,那麼請建議我 –

+0

優秀的工作發佈ddl和樣本數據以及所需的輸出。這裏我不明白的是規則。此外,您發佈的查詢將返回您想要的狀態作爲期望的輸出。如果你能澄清我們可以提供幫助的要求。 –

+0

我試圖在兩張桌子之間進行連接,但是如果發現相同的匹配,就要選擇下一個匹配。正如你在前兩組結果中看到的那樣,在第一個結果中,3-bid與UnId-1和2匹配。 –

回答

0

下面讓我可以的,但仍然在尋找更好的方法,XID是額外場舉辦循環值....

CREATE TABLE #t4 (ID bigint IDENTITY(1,1), bid bigint) 

SELECT 
a.UnID, a.name as aName, a.Id as aId, b.Id as bId,NULL as xid 
INTO #t3 
FROM #t1 a 
JOIN #t2 b ONa.name = b.name 

DECLARE t_cursor CURSOR FOR 
SELECT max(bid),unid 
FROM #t3 
GROUP BY UnId 
DECLARE @bid bigint, @unid bigint 

OPEN t_cursor 

FETCH NEXT FROM t_cursor 
INTO @bid, @unid 
WHILE @@FETCH_STATUS = 0 
BEGIN 

    DECLARE @maxBid BIGINT 
    SET @maxBid = 0 
    SELECT @maxBid = max(bid) 
    FROM #t3 
    WHERE UnId= @unid 
    AND NOT bid IN (SELECT #t4.bid FROM #t4) GROUP BY UnId 

    INSERT into #t4 
    SELECT @maxBid as bid 

    set @maxBid = isnull(@maxBid,0) 
    if(@maxBid != 0) 
    begin 
     update #t3 set xid = @maxBid where unid = @unid 
    end 

    FETCH NEXT FROM t_cursor 
    INTO @bid, @unid 
END 
CLOSE t_cursor; 
DEALLOCATE t_cursor; 

SELECT * FROM #t3 order by unid,bid 

SELECT max(xid),unid from #t3 
group by UnId