0

我有一个下表学生

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
4

3 回答 3

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 |
于 2013-05-02T16:50:33.997 回答
0

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

INSERT INTO StudentReport (ID, StudentID, Report)
SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report
FROM Students
于 2013-05-02T16:55:01.863 回答
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将是DataBase中不存在的新表名

SQL小提琴

于 2013-05-02T17:26:49.497 回答