SQL查询显示下一个日期

时间:2016-04-28 13:43:36

标签: sql sql-server

如何编写将返回下一个日期的查询。

以下是示例,我希望查询填充Next_Date列

由于

Employee_ID    Date        Point       Next_Date
53             07/31/2015    1         12/02/2015   
53             12/02/2015    1         01/12/2016
53             01/12/2016    1         02/10/2016
53             02/10/2016    1         

我使用了以下查询,但获得了Null

SELECT 
    TOP 1 att.attend_date
FROM 
    Attendance att
WHERE 
    att.ID_Employee=att.ID_Employee and
    att.attend_date > att.attend_date
ORDER BY 
          att.attend_date ASC

3 个答案:

答案 0 :(得分:1)

潜在客户应该可以使用,具体取决于您使用的是哪个数据库。

select 
  employee_id, 
  date, 
  point,
  lead(date) over (partition by employee_id order by date) as next_date
from your_table

答案 1 :(得分:0)

您需要一个列来指定订单,因为表没有固有的顺序。它似乎不是由Datasource<-c("Field data", "Participatory data", "Remotely sensed data", "Remotely sensed secondary data", "Secondary data") Number<-c(32,39,55,96,202) Percentage<-c(11,14,19,34,70) DF<-data.frame(Datasource, Number, Percentage) FigDataSourcesFlower<-ggplot(data=DF, aes(x=Datasource, y=Percentage)) + geom_bar(stat="identity", fill = "blue") + theme_bw() + geom_text(aes(y = Percentage + 2.5,label = Percentage)) + coord_polar() + theme(axis.text.x = element_text(size = 15), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title=element_blank()) FigDataSourcesFlower - 列排序的,否则你的前两个记录会因为过去而导致错误hjust

所以我假设您有一个主键来确定订单。

然后你可以使用这个查询(vjust假设sql-server所以必须在其他rdbms中更改):

\n

答案 2 :(得分:0)

假设您使用的是SQL Server,可以使用Row_Number查找符合条件的下一行。

WITH assignmentsSubQuery as
(
    select row_number() over (partition by Employee_ID order by date desc)  as rowId, employee_id, date AS Next_Date
    from Assignments
)
UPDATE
    A 
set
    A.Next_Date = A2.Next_Date
from 
    Assignments A inner join 
    assignmentsSubQuery A1 on (A.employee_id = a1.Employee_ID and A.[Date] = A1.Next_Date) inner join 
    assignmentsSubQuery A2 on (A1.employee_id = a2.Employee_ID and A1.rowId = A2.rowId + 1)