【发布时间】:2017-11-02 09:01:33
【问题描述】:
我有两个如下表:
Table: tb_student
StudentID Mark ConductedDate(datetime)
1 50 02/23/2017 01:15:56 AM
2 60 02/24/2017 01:15:56 AM
3 70 02/23/2017 01:15:56 AM
1 10 02/25/2017 01:15:56 AM
2 50 02/23/2017 01:15:56 AM
2 40 02/25/2017 01:15:56 AM
Table:tb_stvsclass
StudentID ClassID
1 A
2 A
3 B
4 C
Resulted Output should be:
ClassID StudentID 23/02/2017 24/02/2017 25/02/2017 SUM(MARK)
A 1 50 0 10 60
A 2 50 60 40 150
B 3 70 0 0 70
我为此编写了静态查询。
SELECT *
FROM
(
select a.StudentID,a.Mark,a.ConductedDate, b.ClassID
from tb_student a,tb_stvsclass b
where a.StudentID=b.StudentID
) x
pivot
(
sum(Mark)
for ConductedDate in ([02/23/2017 01:15:56 AM], [02/24/2017 01:15:56 AM], [02/25/2017 01:15:56 AM])
) p
但我需要动态 Pivot 查询。因为ConductedDate(datetime datatype) 可能会有所不同。那么如何转化为动态数据透视查询呢?
【问题讨论】:
标签: sql-server tsql sql-server-2005 pivot