小编典典

内部联接SQL Pivot表

sql

我似乎无法内部连接到教师表以获得名字和姓氏。

select * 
from BookingDays bd
inner join Teachers t 
  on t.ID = bd.TeacherID
pivot 
(
  max (bd.BookingDuration) 
  for bd.DayText in ([MONDAY], [TUESDAY], [WEDNESDAY], [THURSDAY], [FRIDAY])
) as MaxBookingDays
where bd.BookingDate >= (SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)) and   
   bd.BookingDate <= (SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 6)) '

我收到的错误消息是

Msg 8156, Level 16, State 1, Line 3
The column 'ID' was specified multiple times for 'MaxBookingDays'.
Msg 4104, Level 16, State 1, Line 4
The multi-part identifier "bd.BookingDate" could not be bound.
Msg 4104, Level 16, State 1, Line 4
The multi-part identifier "bd.BookingDate" could not be bound.

阅读 197

收藏
2021-04-28

共1个答案

小编典典

以下错误是因为您未指定列:

Msg 8156,第16级,状态1,第3行

为“ MaxBookingDays”多次指定了“ ID”列。

因此,我将您的查询稍作更改,如下所示:

select *
from
(
  -- don't use select *, call out your fields
  -- and use a sub-query with your WHERE inside the subquery
  select bd.BookingDuration, bd.Otherfields, t.Fields
  from BookingDays bd
  inner join Teachers t 
    on t.ID = bd.TeacherID
  where bd.BookingDate >= (SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 0)) and   
    bd.BookingDate <= (SELECT DATEADD(ww, DATEDIFF(ww,0,GETDATE()), 6))
) src
pivot 
(
  max (BookingDuration) 
  for DayText in ([MONDAY], [TUESDAY], [WEDNESDAY],[THURSDAY], [FRIDAY])
) as MaxBookingDays
2021-04-28