使用唯一值连接表

时间:2016-03-21 13:14:52

标签: sql-server

下面是这种情况,这是简单的组数据,但加入/分组选择重复数据....

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
  

如果未找到出价则为null

1 个答案:

答案 0 :(得分: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