Sql 从每个组中为每个项目选择可用日期的最佳行
我有这样的数据Sql 从每个组中为每个项目选择可用日期的最佳行,sql,sql-server-2014,Sql,Sql Server 2014,我有这样的数据 Group id Date 1 1 2015-01-01 2 1 2015-01-01 1 1 2015-02-01 2 1 2015-02-01 1 1 2015-03-01 1 2 2015-04-01 2 2 2015-04-01 要为组2中的每个id选择每天的每个记录(如果可用)。如果组2行不可用,则返回该日期的组1记录。对于每个id,始终存在组1记录。所以最终结果应该是 Group id Date
Group id Date
1 1 2015-01-01
2 1 2015-01-01
1 1 2015-02-01
2 1 2015-02-01
1 1 2015-03-01
1 2 2015-04-01
2 2 2015-04-01
要为组2中的每个id选择每天的每个记录(如果可用)。如果组2行不可用,则返回该日期的组1记录。对于每个id,始终存在组1记录。所以最终结果应该是
Group id Date
2 1 2015-01-01
2 1 2015-02-01
1 1 2015-03-01
2 2 2015-04-01
使用
行数
窗口功能
select * from
(
select row_number()over(partition by Date order by Group) as RN,*
from yourtable
) A
Where RN =1
如果一个日期
有多个组=1
,并且如果要返回日期
的所有组=1
记录,则使用密集等级
而不是行数
select distinct max(gid) as gid over(partition by id,[grp_date] order by id), id,grp_date
from test
order by grp_date