繁体   English   中英

选择一列的值到一行 - SQL Server

[英]Select values of a column into one row - SQL Server

我想在一行中选择出现在多行中的列的值,我有表格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   |

我想按StudentIDSongID对记录进行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 |

StudentID-SongID最多有 3 条记录。 我正在使用 SQL Server 2012。

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

;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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM