覆盖T-SQL中的数据

时间:2016-09-14 17:00:28

标签: tsql

我试图找出实现以下结果集的最简洁方法: enter image description here
给出这个输入数据:
enter image description here

请注意,输入数据的第1行和第3行包含相同的项目+存储桶组合。具有“授权来源”的行。应该优先于具有“预测”源的行。用于在生成结果集时匹配项目+桶组合。如果item + bucket组合由于差异源而没有重复,那么这些行将显示在最终结果集中,无论其来源如何。

以下是输入数据的代码:



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;




2 个答案:

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




不确定它是最简洁的方法。

答案 1 :(得分:1)

使用ROW_NUMBER并按[source]字段排序,降序(首先出现“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 ;