2016-09-14 129 views
1

我試圖找出最簡潔的方式來實現以下結果集: enter image description here
給該輸入數據:
enter image description here
覆蓋數據

注意行1和3個輸入數據由相同的項目+桶組合組成。與「任務」的源行應該優先於行以「預測」,用於生成結果集時匹配項+桶組合的來源。在項目+桶組合具有不重複由於差的來源的情況下,這些行是出現在不論其來源的設置的最終結果。

下面是輸入數據的代碼:

declare @t table 
 
(
 
    source varchar(20) not null, 
 
    item int not null, 
 
    bucket date not null, 
 
    quantity int not null, 
 
    primary key clustered (source, item, bucket) 
 
); 
 

 
insert into @t values 
 
('forecast', 8501, '9/1/2016', 100), 
 
('forecast', 8528, '9/1/2016', 100), 
 
('mandate', 8501, '9/1/2016', 200), 
 
('mandate', 8530, '9/1/2016', 200); 
 

 
select * from @t;

回答

1

使用ROW_NUMBER和order by [來源]字段,降(這樣的 「M ...」 出現在前):

declare @t table 
(
    source varchar(20) not null, 
    item int not null, 
    bucket date not null, 
    quantity int not null, 
    primary key clustered (source, item, bucket) 
); 

insert into @t values 
('forecast', 8501, '9/1/2016', 100), 
('forecast', 8528, '9/1/2016', 100), 
('mandate', 8501, '9/1/2016', 200), 
('mandate', 8530, '9/1/2016', 200); 

; WITH QtyRank 
AS (SELECT * 
     , qRank = ROW_NUMBER() OVER(PARTITION BY [item] ORDER BY [source] DESC) 
    FROM @t 
    ) 
SELECT * 
FROM QtyRank 
WHERE QtyRank.qRank = 1 ; 
+0

現在,簡潔! – knot22

1

這工作:

with 
 
overlap as 
 
(
 
    select t2.* 
 
    from @t t1 
 
    inner join @t t2 
 
    on t1.item = t2.item 
 
    and t1.bucket = t2.bucket 
 
    where t1.source = 'forecast' and t2.source = 'mandate' 
 
) 
 
select t.item, t.bucket, t.quantity 
 
from @t t 
 
left outer join overlap o 
 
on t.item = o.item 
 
and t.bucket = o.bucket 
 
where o.item is null 
 
union all 
 
select item, bucket, quantity from overlap;

不知道這是最conci儘管如此。