2017-04-19 39 views
0

感謝您閱讀和/或回覆我的問題。所有幫助讚賞。如何查找用戶未按月份和年份提交的地址

我被要求寫一個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 
+0

mysql **或** sql-server? – SqlZim

+1

創建一個月的表格並對您的S進行左連接urveys。 –

+0

@ AP08爲什麼在Users表上有一個名爲UserId的字段? Table.Users.Id應該是PK,Table.Surveys.UserId FK – leobelones

回答

0

在SQL Server:使用即席months表,cross joinusers,並left 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