无法对存储在数据集中的数据实施数据透视

时间:2014-08-05 05:21:27

标签: c# sql-server dataset pivot-table

我的数据集包含以下结果集:

enter image description here

我想要结果如下:

enter image description here

我尝试使用Pivot但失败了。我试图在.cs文件中的C#代码中执行此操作而不是在sql server过程中。

这是我在SQL Server中尝试过的。它没有给出理想的结果。

    Declare @CourseID int
 Declare @SemID int
 Set @SemID=1
 Set @CourseID=1
 DECLARE @values varchar(max);
SET @values = '';
 If(@SemID=0)
    BEGIN
        SELECT @values = @values +'['+ CAST(PurPose AS varchar(max))+ ']' + ','
        FROM tbFee Where CourseID=@CourseID
        SET @values = SUBSTRING(@values, 1, Len(@values) - 1)
    END
ELSE
    BEGIN
        SELECT @values = @values +'['+ CAST(PurPose AS varchar(max))+ ']' + ','
        FROM tbFee Where SemID=@SemID
        SET @values = SUBSTRING(@values, 1, Len(@values) - 1)
    END

 Declare @st nvarchar(max)
 set @st='''Not Available''';
 declare @q nvarchar(max)
set @q = '
 Select * from(

SELECT     dbo.tbStudent.Name, dbo.tbStudent.RegNo, dbo.tbFee.PID, dbo.tbFee.Purpose, dbo.tbFee.AmountPaid, dbo.tbFee.StudentID, dbo.tbFee.Date, dbo.tbFee.FeeID, 
                      dbo.tbFee.SemID, dbo.tbFee.CourseID, dbo.tbFee.ModeOfPayment, dbo.tbFee.CheckNo, dbo.tbFee.DDNo, dbo.tbFee.HostelDDNo, dbo.tbFee.FRID, 
                      dbo.tbStudent.Parentage, dbo.tbCourse.Name AS Course, ISNULL(dbo.tbSemester.SemName, ' + @st +') AS Semester
FROM         dbo.tbFee INNER JOIN
                      dbo.tbStudent ON dbo.tbFee.StudentID = dbo.tbStudent.StudentID INNER JOIN
                      dbo.tbCourse ON dbo.tbFee.CourseID = dbo.tbCourse.CourseID LEFT OUTER JOIN
                      dbo.tbSemester ON dbo.tbFee.SemID = dbo.tbSemester.SemID 
          ) as x
          pivot (
    max(AmountPaid)
    for Purpose in (' + @values + ')
) as pvt
'

exec (@q)

下面的代码给出了我需要在数据集中填充的第一个结果集,这部分很好。

  SELECT     dbo.tbStudent.Name, dbo.tbStudent.RegNo, dbo.tbFee.PID, dbo.tbFee.Purpose, dbo.tbFee.AmountPaid, dbo.tbFee.StudentID, dbo.tbFee.Date, dbo.tbFee.FeeID, 
                      dbo.tbFee.SemID, dbo.tbFee.CourseID, dbo.tbFee.ModeOfPayment, dbo.tbFee.CheckNo, dbo.tbFee.DDNo, dbo.tbFee.HostelDDNo, dbo.tbFee.FRID, 
                      dbo.tbStudent.Parentage, dbo.tbCourse.Name AS Course, ISNULL(dbo.tbSemester.SemName, ' + @st +') AS Semester
FROM         dbo.tbFee INNER JOIN
                      dbo.tbStudent ON dbo.tbFee.StudentID = dbo.tbStudent.StudentID INNER JOIN
                      dbo.tbCourse ON dbo.tbFee.CourseID = dbo.tbCourse.CourseID LEFT OUTER JOIN
                      dbo.tbSemester ON dbo.tbFee.SemID = dbo.tbSemester.SemID 

首先我需要得到第二个表中显示的结果集,另外我需要在包含第一个表结果的数据集上的c#代码中执行此操作

0 个答案:

没有答案