如何找到用户未按月和年份提交的位置

时间:2017-04-19 18:38:11

标签: sql date

感谢您抽出时间阅读和/或回复我的问题。所有帮助表示赞赏。

我被要求编写一个SQL查询,以找出哪些用户尚未完成特定月份的调查。基本上每个用户必须每月(当月的任何时间)完成一次调查,并将其记录在表格中。

Table.Users

ID  UserID  Name
1   10      Jon Doe
2   20      Jane Doe

Table.Survey

ID  UserID  DateSubmitted
1   10      01/01/2016
2   10      02/02/2016
3   10      03/03/2016
4   10      04/04/2016
5   10      05/05/2016
6   10      06/06/2016

输出(这将显示用户未提交调查的月份和年份。

UserID  Month   Year    DateSubmitted
10      1       2016    01/01/2016
10      2       2016    02/02/2016
10      3       2016    03/03/2016
10      4       2016    04/04/2016
10      5       2016    05/05/2016
10      6       2016    06/06/2016
10      7       2016    NULL
10      8       2016    NULL
10      9       2016    NULL
10      10      2016    NULL
10      11      2016    NULL
10      12      2016    NULL

1 个答案:

答案 0 :(得分:0)

在SQL Server中:使用adhoc months表,cross joinusersleft joinSurvey

declare @StartDate     date = '20160101'
       ,@NumberOfYears int  = 1;

;with Months as (
select top (12*@NumberOfYears) 
      MonthStart = dateadd(month, row_number() over (order by number) -1, @StartDate)
    , MonthEnd   = dateadd(day,-1
        , dateadd(month, row_number() over (order by number), @StartDate))
    , Month = month(dateadd(month, row_number() over (order by number) -1, @StartDate))
    , Year  = year(dateadd(month, row_number() over (order by number) -1, @StartDate))
  from master.dbo.spt_values
)

select u.UserId, m.Month, m.Year, s.DateSubmitted
  from Users u
    cross join Months m
    left join Survey s
      on u.UserId = s.UserId
     and s.DateSubmitted >= m.MonthStart
     and s.DateSubmitted <= m.MonthEnd
where u.UserId = 10