課程表sql
CREATE TABLE [dbo].[demo_Course]( [Cid] [uniqueidentifier] NOT NULL, [CourseName] [varchar](50) NULL, CONSTRAINT [PK_demo_Course] PRIMARY KEY CLUSTERED ( [Cid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
學員表ide
CREATE TABLE [dbo].[demo_Student]( [Sid] [uniqueidentifier] NOT NULL, [Pid] [uniqueidentifier] NULL, [StudentName] [varchar](50) NULL, [JoinDate] [datetime] NULL, [Sex] [int] NULL, [Old] [int] NULL, CONSTRAINT [PK_demo_Student] PRIMARY KEY CLUSTERED ( [Sid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
成績表spa
CREATE TABLE [dbo].[demo_Score]( [Sid] [uniqueidentifier] NOT NULL, [Cid] [uniqueidentifier] NOT NULL, [Score] [int] NOT NULL ) ON [PRIMARY]
行轉列code
Declare @sql varchar(8000) Set @sql = 'Select Sid' Select @sql = @sql + ',max(case CourseName when '''+CourseName+''' then Score else 0 end) ['+CourseName+']' from demo_Course as cj --把全部惟一的科目的名稱都列舉出來 Select @sql = @sql+' from (select s.sid , c.CourseName , s.Score from demo_Course c left join demo_Score s on c.Cid = s.Cid) t group by Sid' print (@sql)
上面這段輸出的SQL以下:blog
Select Sid,max(case CourseName when '數學' then Score else 0 end) [數學],
max(case CourseName when '英語' then Score else 0 end) [英語],
max(case CourseName when '語文' then Score else 0 end) [語文] from
(select s.sid , c.CourseName , s.Score from demo_Course c left join demo_Score s on c.Cid = s.Cid) t group by Sid