SQL Query如何按日期汇总学生记录?

时间:2013-05-02 16:37:36

标签: sql sql-server

我有下表学生

Id  StudentId       Subject         Date          Grade

1   001     Math        02/20/2013  A

2   001     Literature  03/02/2013  B

3   002     Biology     01/01/2013  A

4   003     Biology     04/08/2013  A

5   001     Biology     05/01/2013  B

6   002     Math        03/10/2013  C

我需要将结果导入名为StudentReport另一个表,如下所示。该表是按日期顺序排列的所有学生记录的累积报告。

Id StudentId       Report

1   001     #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013

2   002     #Math;C;03/10/2013#Biology;A;01/01/2013

3   003     #Biology;A;04/08/2013

3 个答案:

答案 0 :(得分:3)

通常,您不会将此数据存储在表中,而是拥有生成报告所需的所有数据。

SQL Server没有简单的方法来生成以逗号分隔的列表,因此您必须使用FOR XML PATH来创建列表:

;with cte as
(
  select id, 
    studentid,
    date,
    '#'+subject+';'+grade+';'+convert(varchar(10), date, 101) report
  from student
) 
-- insert into studentreport
select distinct 
  studentid,
  STUFF(
         (SELECT cast(t2.report as varchar(50))
          FROM cte t2
          where c.StudentId = t2.StudentId
          order by t2.date desc
          FOR XML PATH (''))
          , 1, 0, '')  AS report
from cte c;

请参阅SQL Fiddle with Demo(包括插入新表格)。给出结果:

| ID | STUDENTID |                                                          REPORT |
------------------------------------------------------------------------------------
| 10 |         1 | #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013 |
| 11 |         2 |                         #Math;C;03/10/2013#Biology;A;01/01/2013 |
| 12 |         3 |                                           #Biology;A;04/08/2013 |

答案 1 :(得分:0)

如果您要将“学生”中的数据插入“学生报告”,请尝试:

INSERT INTO StudentReport (ID, StudentID, Report)
SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report
FROM Students

答案 2 :(得分:0)

不使用 CTE 。改善效果。

FOR XML

(select 
min(ID) as ID,
StudentId,
STUFF((select ', '+'#'+s2.Subject+';'+s2.Grade+';'+convert(varchar(25),s2.Date)
from student s2
where s2.StudentId=s1.StudentId
FOR XML PATH (''))
,1,2,'') as report
into t
 from student s1
group by StudentId)
;

select * from t

t 将是数据库中不存在的新表名

<强> SQL Fiddle