我正在使用SQL Server 2012和VS 2012 C# 我设计了数据库表Roll_No,Attend_Date,Attend_Status 同时存储我存储的数据
______________________________________
Roll_No Attend_Date Attend_Status
---------------------------------------
1 04-01-14 1
2 04-01-14 1
3 04-01-14 1
1 05-01-14 0
2 05-01-14 1
3 05-01-14 0
1 06-01-14 1
2 06-01-14 1
3 06-01-14 1
----------------------------------------
但我必须像这样在网格视图中显示
__________________________________________________________________
Roll_No 04-01-14 05-01-14 06-01-14 07-01-14
-------------------------------------------------------------------
1 1 0 1 1
2 1 1 1 1
3 1 0 1 1
-------------------------------------------------------------------
你能帮帮我吗?
我怎样才能达到这个结果..
答案 0 :(得分:2)
您可以通过在执行PIVOT时将每个日期列为列名称或使用动态SQL生成列列表然后应用PIVOT来执行此操作。
PIVOT is used to change row data to columns
create table #attendance (rollno int,attend_date varchar(30),attend_status int)
insert into #attendance values(1,'04-01-14',1)
insert into #attendance values(2,'04-01-14',1)
insert into #attendance values(3,'04-01-14',0)
insert into #attendance values(1,'05-01-14',1)
insert into #attendance values(2,'05-01-14',0)
insert into #attendance values(3,'05-01-14',1)
insert into #attendance values(1,'06-01-14',1)
insert into #attendance values(2,'06-01-14',1)
insert into #attendance values(3,'06-01-14',0)
Declare @colList varchar(max)
Declare @qry varchar(max)
SET @colList = STUFF((SELECT distinct ',' + QUOTENAME(c.Attend_Date)
FROM #attendance c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @qry = 'SELECT rollno,'+@colList+'
FROM (
SELECT Rollno,attend_date,attend_status
FROM #attendance
) as s
PIVOT
(
MAX(Attend_Status)
FOR Attend_Date IN (' + @colList + ')
) pvt '
EXEC(@qry)
drop table #attendance
<强>输出强>
Rollno 04-01-14 05-01-14 06-01-14
1 1 1 1
2 1 0 1
3 0 1 0
现在您可以在GridView中找到此结果集