1

我有一张attendance表,其中包含学生的出勤日期和出勤状态。

有没有办法显示这样的摘要:

Student 20-09-2012 21-09-2012 22-09-2012 23-09-2012
  xyz       P          A          P           P
  abc       P          P          P           P

通过 SQL Server 查询?

我已经尝试过,PIVOT但由于聚合函数它不起作用。

4

3 回答 3

1

我尝试过使用 PIVOT,但由于聚合函数而无法正常工作。

您可以MAX像这样使用聚合函数:

SELECT t.StudentName,
  MAX(CASE WHEN t.Date = '20120920' THEN t.Status END) AS '20-09-2012',
  MAX(CASE WHEN t.Date = '20120921' THEN t.Status END) AS '21-09-2012',
  MAX(CASE WHEN t.Date = '20120922' THEN t.Status END) AS '22-09-2012',
  MAX(CASE WHEN t.Date = '20120923' THEN t.Status END) AS '23-09-2012'
FROM Attendence t
GROUP BY t.StudentName
于 2012-09-23T08:56:55.637 回答
1

你的问题让我想起了我必须解决的类似问题。使用动态 SQL,您的问题解决如下

-- create list of all dates 
DECLARE @dates varchar(1000) = ''
SELECT @dates = @dates + ',[' + CAST(t.[date] as varchar)+']'
FROM ( SELECT DISTINCT [date] FROM Attendance) t

-- remove first comma
IF LEN(@dates)>1 SET @dates = RIGHT(@dates,LEN(@dates)-1)


-- create query with UNPIVOT and PIVOT
 exec('SELECT 
        StudentName,'+
        @dates+
   'FROM(
        SELECT  
            [date],
            [stat],
            StudentName 
        FROM 
            (SELECT 
                    [date],
                    [status],
                    StudentName 
                FROM 
                    Attendance
            ) AS t
        UNPIVOT 
            ( stat FOR s in ([status])) unpvt
        ) dummy
    PIVOT 
        (
            MAX(stat) FOR [date] in ('+@dates+')
        ) pvt
    ORDER BY StudentName;');

那是您请求的SqlFiddle

于 2012-09-23T10:56:39.113 回答
0
DECLARE @DynamicPivotQuery AS NVARCHAR(max) 
DECLARE @ColumnName AS NVARCHAR(max) 

SELECT a.grno, 
       a.a_date [Date], 
       a.status, 
       s.first_name, 
       s.last_name 
INTO   #pivotdata 
FROM   attendance_master AS a, 
       student_master AS s 
WHERE  sid = " & dd_sub.selecteditem.value & " 
       AND s.grno = a.grno 
       AND a.a_date >= '" & txtdate1.Text & "' 
       AND a.a_date <= '" & txtdate2.Text & "' 
GROUP  BY a.grno, 
          a.status, 
          a.a_date, 
          s.last_name, 
          s.first_name 

SELECT @ColumnName = Isnull(@ColumnName + ',', '') 
                     + Quotename([date]) 
FROM   (SELECT DISTINCT [date] 
        FROM   #pivotdata) AS Dates 

SET @DynamicPivotQuery = 'SELECT grno,first_name,last_name,' 
                         + @ColumnName 
                         + 'FROM #PivotData PIVOT(sum(status) FOR [Date] IN (' 
                         + @ColumnName + ')) AS PVTTable1' 

EXEC Sp_executesql 
  @DynamicPivotQuery 

在此处输入图像描述

于 2016-04-01T19:38:07.300 回答