2016-09-14 131 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尽管如此。