将列的值选择为一行 - SQL Server

时间:2015-09-24 04:22:34

标签: sql sql-server database

我想在一行中选择多行中显示的列的值,我有表<textarea name="mm" id="mm" rows="5" placeholder="NA if not applicable" required="required"></textarea>

Solution

我想按| StudentID | SolutionDate | SolutionTime | SongID | ---------------------------------------------------- | 0824616 | 2015-09-20 | 00:07:00 | 01 | | 0824616 | 2015-09-20 | 00:05:00 | 02 | | 0824616 | 2015-09-21 | 00:07:40 | 01 | | 0824616 | 2015-09-21 | 00:10:00 | 03 | | 0824616 | 2015-09-23 | 00:04:30 | 03 | | 0824616 | 2015-09-23 | 00:11:30 | 03 | StudentID对记录进行分组。

预期输出为:

SongID

| StudentID | SongID | TimeA | TimeB | TimeC | ------------------------------------------------------- | 0824616 | 01 | 00:07:00 | 00:07:40 | NULL | | 0824616 | 02 | 00:05:00 | NULL | NULL | | 0824616 | 03 | 00:10:00 | 00:04:30 | 00:11:30 | 最多有3条记录。我正在使用SQL Server 2012。

1 个答案:

答案 0 :(得分:1)

首先尝试使用窗口函数对行进行编号,然后使用条件聚合:

;with cte as(select *, row_number() over(partition by studentid, songid 
                        order by solutiondate, solutiontime) rn from tablename)

select studentid,
       songid,
       max(case when rn = 1 then solutiontime end) as timea,
       max(case when rn = 2 then solutiontime end) as timeb,
       max(case when rn = 3 then solutiontime end) as timec
from cte
group by studentid, songid