按创建时间排序的sql订单asc

kninwzqo  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(343)

我有个问题:

SELECT 
    p.[TerminalId],
    Keys = JSON_QUERY('[' + string_agg(json_query('{"Point":"' + p.Location.STAsText() + '","CreatedDateTime":"' + cast(p.CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
    (SELECT
         geography::STGeomFromText(Location.STAsText(), 4326) as Location,
         [CreatedDateTime],
         [TerminalId],
         ROW_NUMBER() OVER (ORDER BY [CreatedDateTime] ASC) AS RowNum
     FROM 
         [Magicar_Route].[dbo].[PacketLocations]) AS p
GROUP BY 
    p.[TerminalId]

我想要 p.Location 排序依据 CreatedDateTime ascKeys json列但在查询之后 Location 未排序 ASC ?
如何根据createddatetime asc排序我的位置?
我将查询更改为:

WITH NewScores AS 
(
    SELECT
        geography::STGeomFromText(Location.STAsText(), 4326) AS Location,
        [CreatedDateTime],
        [TerminalId]
    FROM
        [Magicar_Route].[dbo].[PacketLocations]
    ORDER BY 
        [CreatedDateTime] ASC
)
SELECT 
    [TerminalId],
    Keys = JSON_QUERY('['+ string_agg(json_query('{"Point":"' + Location.STAsText() + '","CreatedDateTime":"' + cast(CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
    NewScores

但不幸的是我犯了这个错误:
味精1033,15级,状态1,第100行
order by子句在视图、内联函数、派生表、子查询和公共表表达式中无效,除非还指定了top、offset或for xml。

j0pj023g

j0pj023g1#

不要将order按放入cte中,而是将其用于下面的查询

WITH NewScores AS 
(
    SELECT
        geography::STGeomFromText(Location.STAsText(), 4326) AS Location,
        [CreatedDateTime],
        [TerminalId]
    FROM
        [Magicar_Route].[dbo].[PacketLocations]
)
SELECT 
    [TerminalId],
    Keys = JSON_QUERY('['+ string_agg(json_query('{"Point":"' + Location.STAsText() + '","CreatedDateTime":"' + cast(CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
    NewScores
ORDER BY 
    [CreatedDateTime] ASC

相关问题