34,576
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#product') is null
drop table #product
Go
Create table #product([productName] nvarchar(28),[createdDate] Date)
Insert #product
select N'product1','2016-1-2' union all
select N'product1','2016-3-1' union all
select N'product1','2016-3-2' union all
select N'product1','2016-3-15' union all
select N'product2','2016-2-1'
GO
if not object_id(N'Tempdb..#productConfig') is null
drop table #productConfig
Go
Create table #productConfig([productname] nvarchar(28),[configname] nvarchar(27),[configDate] Date)
Insert #productConfig
select N'product1',N'config1','2015-1-1' union all
select N'product1',N'config2','2016-1-3' union all
select N'product1',N'config3','2016-3-5' union all
select N'product2',N'configm','2016-1-15'
Go
--测试数据结束
SELECT t.productName,
t.createdDate,
t.configname
FROM
(
SELECT a.*,
b.configname,
ROW_NUMBER() OVER (PARTITION BY a.productName,
a.createdDate
ORDER BY ABS(DATEDIFF(DAY, a.createdDate, b.configDate))
) AS rn
FROM #product a
JOIN #productConfig b
ON a.productName = b.productname
WHERE a.createdDate>b.configDate
) t
WHERE rn = 1;
--测试数据
if not object_id(N'Tempdb..#product') is null
drop table #product
Go
Create table #product([productName] nvarchar(28),[createdDate] Date)
Insert #product
select N'product1','2016-1-2' union all
select N'product1','2016-3-1' union all
select N'product1','2016-3-2' union all
select N'product1','2016-3-15' union all
select N'product2','2016-2-1'
GO
if not object_id(N'Tempdb..#productConfig') is null
drop table #productConfig
Go
Create table #productConfig([productname] nvarchar(28),[configname] nvarchar(27),[configDate] Date)
Insert #productConfig
select N'product1',N'config1','2015-1-1' union all
select N'product1',N'config2','2016-1-3' union all
select N'product1',N'config3','2016-3-5' union all
select N'product2',N'configm','2016-1-15'
Go
--测试数据结束
SELECT t.productName,
t.createdDate,
t.configname
FROM
(
SELECT a.*,
b.configname,
ROW_NUMBER() OVER (PARTITION BY a.productName,
a.createdDate
ORDER BY ABS(DATEDIFF(DAY, a.createdDate, b.configDate))
) AS rn
FROM #product a
JOIN #productConfig b
ON a.productName = b.productname
) t
WHERE rn = 1;
select
tmp.productName
,tmp.createdDate
,tmp.configname
,tmp.configDate
(
SELECT p.productName
,p.createdDate
,pc.configname
,pc.configDate
, row_number() over(partition by productName order by datediff(dd,pc.configDate,p.createdDate)) as row
FROM product as p
left join
productConfig as pc
on
p.productName=pc.createdDate
)as tmp
where row=1
select
tmp.productName
,tmp.createdDate
,tmp.configname
,tmp.configDate
(
SELECT p.productName
,p.createdDate
,pc.configname
,pc.configDate
, row_number() over(partition by productName order by datediff(dd,configDate,configname ) as row
FROM product as p
left join
productConfig as pc
on
p.productName=pc.createdDate
)as tmp
where row=1