行结果操作

时间:2018-02-02 06:47:49

标签: sql sql-server tsql sql-server-2012

我有一个检索此数据的现有查询:

Key Type TextF
--- ---- ------
1   R    NULL
1   T    TEST
1   T    TEST2
2   R    NULL
2   T    FOO
3   R    NULL

场景:
行类型RNULL上始终为TextF。但是,如果Key存在T类型数据,我应将TextF放在R数据上,并将其与CRLFchar(13)相关联

  

基于给定数据的预期输出:

Key Type TextF
--- ---- ----------
1   R    TEST TEST2
2   R    FOO
3   R    NULL

如何通过查询实现此目的?我试图让我现有的查询成为一个子查询但我似乎无法使它工作。

SELECT T0.*, *formatting here* FROM ( [myQuery] ) T0

4 个答案:

答案 0 :(得分:2)

我认为这不是最佳解决方案,但您可以使用STUFF功能来达到预期效果:

SELECT t1.[Key],
    'R' [Type],
    STUFF((SELECT ' ' + t2.[TextF]
    FROM yourTable t2
    WHERE t2.[Key] = t1.[Key]
    FOR XML PATH('')), 1, 1, '') [TextF]
FROM yourTable t1
GROUP BY t1.[Key]

答案 1 :(得分:2)

你可以使用它。

DECLARE @MyTable TABLE ([Key] INT, Type VARCHAR(5), TextF VARCHAR(100))
INSERT INTO @MyTable VALUES
(1   ,'R', NULL),
(1   ,'T', 'TEST'),
(1   ,'T', 'TEST2'),
(2   ,'R', NULL),
(2   ,'T', 'FOO'),
(3   ,'R', NULL)

SELECT 
    T.[Key], 
    T.Type,
    CASE WHEN Type = 'R' THEN REPLACE(STUFF(X.TextF,1,1,''),'|', CHAR(13)) ELSE T.TextF END TextF 
FROM @MyTable T
        OUTER APPLY( SELECT '|' + TextF FROM @MyTable T1 
                        WHERE T.[Key] = T1.[Key] 
                            AND T1.Type <> 'R'
                            AND T1.TextF IS NOT NULL FOR XML PATH('')) X(TextF)
WHERE T.Type = 'R'

结果:

Key         Type  TextF
----------- ----- -------------
1           R     TEST
                  TEST2
2           R     FOO
3           R     NULL

答案 2 :(得分:2)

在SQL Server 2017中,您可以使用新的内置函数STRING_AGG

SELECT T0.[Key], T0.[Type],

(SELECT STRING_AGG (T1.TextF, CHAR(13)) AS TextF
   FROM [myTable] T1
  WHERE T1.[Type]='T' AND T1.[Key]=T0.[Key]
) TextF

FROM [myTable] T0
WHERE T0.[Type]='R'

答案 3 :(得分:1)

与其他解决方案略有不同 -

DECLARE @MyTable TABLE ([Key] INT, Type VARCHAR(5), TextF VARCHAR(100))
INSERT INTO @MyTable VALUES
(1   ,'R', NULL),
(1   ,'T', 'TEST'),
(1   ,'T', 'TEST2'),
(2   ,'R', NULL),
(2   ,'T', 'FOO'),
(3   ,'R', NULL)

SELECT 
    T.[Key], 
    T.Type,
    STUFF 
                ((
                    SELECT '  ' + TextF
                    FROM @MyTable a
                    WHERE ( a.[Key] = T.[Key] )
                    FOR XML PATH('')
                ) ,1,2,'') 
                AS cusr
FROM @MyTable T
WHERE T.Type = 'R'

<强>输出

Key         Type  cusr
----------- ----- --------------
1           R     TEST  TEST2
2           R     FOO
3           R     NULL

(3 rows affected)