SQL 连接具有相同 ID 和最新日期的行

SQL concat rows with same ID and newest date

我正在寻求帮助以查询我的应用程序消息的输出。我有一个查询,它获取每条消息的行并将它们连接在一起形成一个句子。但是,我的某些消息编号有两条或更多条消息,在这种情况下,我只想要最新日期的消息。我当前的代码通过按每个消息编号的顺序将行号连接在一起并按 MSG_NUM 的顺序输出它们来输出一个句子中的所有消息。我已经添加了 MSG_START_DATE 的排序,但正如预期的那样,这仍然给了我两个。我怎样才能为每个串联的消息行做一个 select 最大值?

以下是我正在使用的字段:

MSG_NUM | MSG_START_DATE  | MSG_LINE_NUM | MSG_TEXT

1       | 2010-01-15      | 1            | Invalid operation
1       | 2010-01-15      | 2            | try again
1       | 2014-02-21      | 1            | Invalid input
1       | 2014-02-21      | 2            | try again

这是我当前的代码:

Select distinct ST2.[MSG_NUM],
substring(
    (
        (Select ' '+LTRIM(RTRIM(ST1.[MSG_TEXT]))  AS [text()]
        From database..messages ST1 
        Where ST1.[MSG_NUM] = ST2.[MSG_NUM]
        ORDER BY ST1.[MSG_START_DATE], ST1.[MSG_LINE_NUM]
        For XML PATH (''),root('xmlchar'), type).value('/xmlchar[1]','varchar(max)')
    ), 2, 2000) [Message]
From database..messages ST2 order by ST2.[MSG_NUM]

这是我收到的输出:

1 Invalid operation try again Invalid input try again

我只想要输出:

1 Invalid input try again

关于如何执行此操作的任何想法?

你按日期过滤怎么样?

Select distinct ST2.[MSG_NUM],
substring(
    (
        (Select ' '+LTRIM(RTRIM(ST1.[MSG_LINE_NUM]))  AS [text()]
        From database..messages ST1 
        Where ST1.[MSG_NUM] = ST2.[MSG_NUM]
          AND ST1.[MSG_START_DATE] = (SELECT MAX(ST3.[MSG_START_DATE])
                                      FROM database..messages ST3
                                      WHERE ST2.[MSG_NUM] = ST3.[MSG_NUM]
                                     )
        ORDER BY ST1.[MSG_LINE_NUM]
        For XML PATH (''),root('xmlchar'), type).value('/xmlchar[1]','varchar(max)')
    ), 2, 2000) [Message]
From database..messages ST2 order by ST2.[MSG_NUM]

更好的是,只需在传递给您的查询之前进行过滤

WITH maxd
AS (
    SELECT *
        ,MAX(MSG_START_DATE) OVER (PARTITION BY [MSG_NUM]) AS maxdate
    FROM DATABASE..messages
    )
    ,filter
AS (
    SELECT *
    FROM maxd
    WHERE MSG_START_DATE = maxdate
    )
SELECT DISTINCT ST2.[MSG_NUM]
    ,substring((
            (
                SELECT ' ' + LTRIM(RTRIM(ST1.[MSG_LINE_NUM])) AS [text()]
                FROM filter ST1
                WHERE ST1.[MSG_NUM] = ST2.[MSG_NUM]
                ORDER BY ST1.[MSG_LINE_NUM]
                FOR XML PATH('')
                    ,root('xmlchar')
                    ,type
                ).value('/xmlchar[1]', 'varchar(max)')
            ), 2, 2000) [Message]
FROM filter ST2
ORDER BY ST2.[MSG_NUM]