我想使用sql server pivot生成每周时间表。
我的数据库有这些表。
create table Students
(
StudentID int identity primary key,
Name nvarchar(50)
)
create table Times
(
TimeID int identity primary key
,Name nvarchar(10)
)
create table Days
(
DayID int identity primary key
,Name nvarchar(20)
)
create table TimeTable
(
StudentID int references Students(StudentID)
,TimeID int references Times(TimeID)
,DayID int references Days(DayID)
,Value nvarchar(50)
)
insert Times values('t1')
insert Times values('t2')
insert Times values('t3')
insert Days values('sunday')
insert Days values('monday')
insert Days values('tuesday')
insert Days values('wednesday')
insert Days values('thursday')
insert Days values('friday')
insert Days values('saturday')
我想要列(DayID,DayName,t1,t2,t3)
我正在使用此查询,但由于使用Max(Value)聚合函数,当我将记录插入TimeTable表时,此查询显示列t1,t2和t3的一个值。但是t2和t3应为null
SELECT *
FROM (SELECT dbo.Days.DayID, dbo.Days.Name, dbo.Times.Name AS Expr1, dbo.TimeTable.Value
FROM dbo.Times CROSS JOIN
dbo.Days LEFT OUTER JOIN
dbo.TimeTable ON dbo.Days.DayID = dbo.TimeTable.DayID) AS d_1
PIVOT (max (Value) FOR [Expr1]
IN (t1, t2, t3)) AS P
例如,在执行这些cmds之后,显示所有列的asp值。
insert Students values('ahmad')
insert TimeTable values(1,1,1,'asp')
答案 0 :(得分:0)
你错过了从TimeTable到Times的比赛:
AND dbo.Times.TimeID = dbo.TimeTable.TimeID
答案 1 :(得分:0)
你非常接近试试这个:
create table #Students
(
StudentID int identity primary key,
Name nvarchar(50)
)
create table #Times
(
TimeID int identity primary key
,Name nvarchar(10)
)
create table #Days
(
DayID int identity primary key
,Name nvarchar(20)
)
create table #TimeTable
(
StudentID int references #Students(StudentID)
,TimeID int references #Times(TimeID)
,DayID int references #Days(DayID)
,Value nvarchar(50)
)
insert #Times values('t1')
insert #Times values('t2')
insert #Times values('t3')
insert #Days values('sunday')
insert #Days values('monday')
insert #Days values('tuesday')
insert #Days values('wednesday')
insert #Days values('thursday')
insert #Days values('friday')
insert #Days values('saturday')
insert #Students values('ahmad')
insert #TimeTable values(1,1,1,'asp')
SELECT *
FROM
(
SELECT d.DayID, d.Name, t.Name AS Expr1, tt.Value
FROM #Times t
CROSS JOIN #Days d
LEFT OUTER JOIN #TimeTable tt
ON d.DayID = tt.DayID
AND t.TimeID = tt.TimeID) AS d_1
PIVOT (max (Value) FOR [Expr1]
IN (t1, t2, t3)) AS P
drop table #Students
drop table #Times
drop table #Days
drop table #TimeTable