大家。我不能做以下查询。请帮忙。 初始数据和输出位于以下excel initial data/output google/drive
这是逻辑:对于'Rest'= 2500,它取最小值'Date',将其递增1并将其放入输出的Date1列; Date2收到下一个'Rest'值(1181,85)的日期的最小值..依此类推:Date1收到'Rest'(1181,85)'Date'(14.01.2013)的最小值加1( 15.01.2013)等等。它不应该对'Rest'值为零进行上述操作(它应该跳过它)。我们最初不能删除'Rest'值为零的行,因为他们的Date在Date2中使用,如上所述。有许多'accNumber',它应该列出所有这些。请帮忙。我希望你明白,如果不是要求更多细节。提前致谢。我正在使用SQL服务器。
答案 0 :(得分:0)
如果我理解正确,您希望按休息编号对项目进行分组,然后显示最短日期+ 1天,以及“下一个”休息编号的最短日期。当Rest号码在两个不同的地方为0时,你期待发生什么?
with Base as
(
select t.AccNum,
t.Rest,
DATEADD(day, 1, MIN(t.Date)) as [StartDate],
ROW_NUMBER() OVER (ORDER BY MIN(t.Date)) as RowNumber
from Accounts t
where t.Rest <> 0
group by t.AccNum, t.Rest
)
select a.AccNum, a.Rest, a.StartDate, DATEADD(DAY, -1, b.StartDate) as [EndDate]
from Base a
left join Base b
on a.RowNumber = b.RowNumber - 1
order by a.[StartDate]
如果Rest数字可能被进一步向下复制,但需要单独一个项目,那么我们在初始选择查询中需要更加聪明。
with Base as
(
select b.AccNum, b.Rest, MIN(DATEADD(day, 1, b.Date)) as [StartDate], ROW_NUMBER() OVER (ORDER BY MIN(Date)) as [RowNumber]
from (
select *, ROW_NUMBER() OVER (PARTITION BY Rest ORDER BY Date) - ROW_NUMBER() OVER (ORDER BY Date) as [Order]
from Accounts a
-- where a.Rest <> 0
-- If we're still filtering out Rest 0 uncomment the above line
) b
group by [order], AccNum, Rest
)
select a.RowNumber, a.AccNum, a.Rest, a.StartDate, DATEADD(DAY, -1, b.StartDate) as [EndDate]
from Base a
left join Base b
on a.RowNumber = b.RowNumber - 1
order by a.[StartDate]
两个查询的结果:
Account Number REST Start Date End Date
45817840200000057948 2500 2013-01-01 2013-01-14
45817840200000057948 1181 2013-01-15 2013-01-31
45817840200000057948 2431 2013-02-01 2013-02-09
45817840200000057948 1563 2013-02-10 NULL