如何以自定义格式检索数据

时间:2020-02-17 16:12:38

标签: sql sql-server

  1. 我检索了一些数据,如下所示(图像01)。

我使用了以下查询:

SELECT TOP (3) no, co, cdate, year 
FROM main_backup 
WHERE (no = 41505) 
ORDER BY cdate DESC

Image 01

  1. 但是我想要那样,如下图所示(图02)

image 02

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合和窗口函数:

select no,
       max(case when seqnum = 1 then total end) as total_1,
       max(case when seqnum = 1 then cdate end) as date_1,
       max(case when seqnum = 2 then total end) as total_2,
       max(case when seqnum = 2 then cdate end) as date_2,
       max(case when seqnum = 3 then total end) as total_3,
       max(case when seqnum = 3 then cdate end) as date_3
from (select t.*,
             row_number() over (partition by no order by cdate desc) as seqnum
      from t
     ) t
group by no