Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何以自定义格式检索数据 我检索了一些数据,如下所示(图01)_Sql_Sql Server - Fatal编程技术网

Sql 如何以自定义格式检索数据 我检索了一些数据,如下所示(图01)

Sql 如何以自定义格式检索数据 我检索了一些数据,如下所示(图01),sql,sql-server,Sql,Sql Server,我使用了这个查询: SELECT TOP (3) no, co, cdate, year FROM main_backup WHERE (no = 41505) ORDER BY cdate DESC 但我想要这样,就像下面这种类型(图02) 您可以使用条件聚合和窗口函数: select no, max(case when seqnum = 1 then total end) as total_1, max(case when seqnum = 1 then

我使用了这个查询:

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

  • 但我想要这样,就像下面这种类型(图02)

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

    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
    

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

    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