我想要不同的数字,并使用datetime升序选择列

8ehkhllq  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(206)

有一张table

1001  vsp,science,BBA  25-05-2020
1001  vsp,Maths,Btech  26-05-2020
1001  vsp,Maths,Btech  27-05-2020
1002  hyd,science,BBA  24-05-2020
1002  blr,Maths,Btech  25-05-2020

我想要

1001  vsp,science,bba   vsp,Maths,Btech    vsp,Maths,Btech
uinbv5nw

uinbv5nw1#

你需要一个我最喜欢的组合来实现你的目标:
cte(创建适当的子请求):https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql
行号(为您的行排序):https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql
透视(透视结果):https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot
现在解决方案是:

WITH orderedCourse AS
(
    SELECT  GroupId,
            CourseLabel,
            ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY CourseDate) AS CourseNumber
    FROM @myCourses
)
SELECT TOP (1) GroupId, [1], [2], [3], [4]
FROM    
        (
            SELECT  GroupId,
                    CourseLabel,
                    CourseNumber
            FROM orderedCourse
        ) AS src
        PIVOT
        (
            MIN(CourseLabel) -- default agregate
            FOR CourseNumber IN ([1], [2], [3], [4] /*... if you have more courses by group*/)
        ) AS pvt
ORDER BY GroupId

结果如下:

1001  vsp,science,BBA  vsp,Maths,Btech  vsp,Maths,Btech  NULL

我使用以下代码声明表:

INSERT INTO @myCourses
SELECT 1001, 'vsp,science,BBA', CAST('25-05-2020' AS date) UNION ALL
SELECT 1001, 'vsp,Maths,Btech', CAST('26-05-2020' AS date) UNION ALL
SELECT 1001, 'vsp,Maths,Btech', CAST('27-05-2020' AS date) UNION ALL
SELECT 1002, 'yd,science,BBA', CAST('24-05-2020' AS date) UNION ALL
SELECT 1002, 'blr,Maths,Btech', CAST('25-05-2020' AS date);

SELECT  GroupId,
        CourseLabel,
        CourseDate,
        ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY CourseDate) AS CourseNumber
FROM @myCourses;
8yoxcaq7

8yoxcaq72#

只需将条件聚合用于 row_number() :

select col1,
       max(case when seqnum = 1 then col2 end),
       max(case when seqnum = 2 then col2 end),
       max(case when seqnum = 3 then col2 end)
from (select t.*,
             row_number() over (partition by col1 order by col3) as seqnum
      from t
     ) t
group by col1;

这与字符串聚合无关。它也不需要过多的子查询和cte。

相关问题