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

时间:2015-11-21 01:06:47

标签: sql date sql-server-2012 rows concat

我正在寻找帮助,查询我的应用程序消息的输出。我有一个查询,它接受每条消息的行,并将它们连接在一起形成一个句子。但是,我的一些消息号码有两条或更多消息,在这种情况下,我只希望消息具有最新日期。我当前的代码通过将行号连接在一起来输出句子中的所有消息,以便为每个消息号输入,并按MSG_NUM的顺序输出它们。我已经按照MSG_START_DATE添加了订单,但正如预期的那样仍然给了我两个。如何为每个连接的消息行执行select max?

以下是我与之合作的字段:

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无效操作再试一次无效输入再试一次

我只想要输出:

  

1无效输入再次尝试

关于我如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

按日期过滤怎么样?

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]