内部连接SQL Pivot表

时间:2022-09-21 22:22:59

I cant seem to inner join to a teachers table in order to get the first and surname.

我似乎不能为了得到第一名和姓而与老师的桌子内部连接。

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)) '

The error message I get is -

我得到的错误信息是-

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.

1 个解决方案

#1


4  

The error below is because you are not specifying your columns:

下面的错误是因为您没有指定您的列:

Msg 8156, Level 16, State 1, Line 3

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

The column 'ID' was specified multiple times for 'MaxBookingDays'.

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

So I would change your query slightly to something like this:

我把你的问题稍微改一下

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

#1


4  

The error below is because you are not specifying your columns:

下面的错误是因为您没有指定您的列:

Msg 8156, Level 16, State 1, Line 3

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

The column 'ID' was specified multiple times for 'MaxBookingDays'.

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

So I would change your query slightly to something like this:

我把你的问题稍微改一下

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