我想用日期时间升序来选择不同的数字作为列。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我想用日期时间升序来选择不同的数字作为列。相关的知识,希望对你有一定的参考价值。
有一桌
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
答案
你需要一个我最喜欢的组合来实现你的目标。
- CTE(创建适当的子请求)。https:/docs.microsoft.comen-ussqlt-sqlquerieswith-commontable-expression-transact-sql。
- ROW_NUMBER(对你的行进行排序)。https:/docs.microsoft.comen-ussqlt-sqlfunctionsrow-number-transact-sql。
- PIVOT(对结果进行透视)。https:/docs.microsoft.comen-ussqlt-sqlqueriesfrom-using-pivot andunpivot。
而现在的解决方案。
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;
另一答案
只要用条件聚合与 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。
以上是关于我想用日期时间升序来选择不同的数字作为列。的主要内容,如果未能解决你的问题,请参考以下文章