将2行合并为一行

时间:2017-11-01 11:49:31

标签: sql-server

我想将两行查询结果组合成一行,其中第二行中一列的输出将填充到第一行中的一列中。

select INCDNT_TXT
    , INCDNT_TXT 
    , INCDNT_ID
    , SUBMIT_By
    , cast (SUBMIT_Date as date)
FROM
INCDNT_DATA join INCDNT
on INCDNT.INCDNT_ID = INCDNT_DATA.INCDNT_ID
where INCDNT_DATA.INCDNT_ID
 = 'Test' and (INCDNT_TXT_Detail = 'Account Name' or INCDNT_TXT_Detail = 'country')

输出是:

INCDNT_TXT INCDNT_TXT   INCDNT_ID   SUBMIT_By   SUBMIT_Date
Company1   Company1     Test         Peter       08/29/2017
France     France       Test         Peter       08/29/2017

我想输出如下:

INCDNT_TXT INCDNT_TXT2  INCDNT_ID   SUBMIT_By   SUBMIT_Date
Company1   France       Test         Peter       08/29/2017

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果您确定每个INCDNT_IDSUBMIT_BySUBMIT_Date组只有两条记录,那么您可以尝试按以下三列进行汇总:

SELECT
    MIN(INCDNT_TXT) AS INCDNT_TXT,
    MAX(INCDNT_TXT) AS INCDNT_TXT2,
    INCDNT_ID
    SUBMIT_By
    CASt(SUBMIT_Date AS date)
FROM INCDNT_DATA
INNER JOIN INCDNT
    ON INCDNT.INCDNT_ID = INCDNT_DATA.INCDNT_ID
WHERE
    INCDNT_DATA.INCDNT_ID = 'Test' AND
    (INCDNT_TXT_Detail = 'Account Name' OR INCDNT_TXT_Detail = 'country')
GROUP BY
    INCDNT_ID, SUBMIT_By, CAST(SUBMIT_Date AS date)