0
USE [SAFLA]

DECLARE 
      @cols AS NVARCHAR(MAX)
    , @query AS NVARCHAR(MAX)

SET @cols = STUFF((
    SELECT DISTINCT ',' + QUOTENAME(w.week_range)
    FROM Weekly_Attendance AS w
    FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

SET @query = '
    SELECT stu_id, name, ' + @cols + ' 
    FROM (
        SELECT 
              stu.stu_id
            , stu.name
            , w.total_present_lec
            , w.week_range
        FROM Student_Registration AS stu 
        JOIN Weekly_Attendance w ON stu.stu_id = w.stu_id
    ) x
    PIVOT 
    (
        SUM(total_present_lec)
        FOR week_range in (' + @cols + ')
        --GROUP BY total_present_lec
    ) p'

EXECUTE (@query)

这是我想与 ASP.NET 页面集成的 sql 查询。

4

0 回答 0