干净的代码与一堆临时表

时间:2017-02-02 16:44:09

标签: sql-server

TableA -- list of objects
--------
Rec1
Rec2
Rec3

TableB  -- list of TONS of details A->B = 1->MMM
--------
Rec1, data..., String1
Rec1, data..., String1
Rec1, data..., String1
Rec1, data..., String2
Rec2, data..., String1
Rec2, data..., String1
Rec3, data..., String1
Rec3, data..., String1
Rec3, data..., String2
Rec3, data..., String2
Rec3, data..., String3

通过剪切一些细节,查询将表B减少到更少的记录数,留下1-gt; M

QueryResult
------------
Rec1, String1
Rec1, String2
Rec2, String1
Rec3, String1
Rec3, String2
Rec3, String3

尝试构建

Final
---------
Rec1, String1 + String2
Rec2, String1
Rec3, String1 + String2 + String3

我尝试为每个不同的String添加列,适当地打包字符串,然后将各个字符串连接到摘要列。虽然这很有效,但它看起来很丑陋,让人想起我的工具箱中只有一把锤子。

使用除了我的大锤之外的其他工具是否有更优雅的解决方案?

非常感谢评论和见解。 谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用for xml执行此操作,将原始TableA加入QueryResult

declare @TableA table(TableA nvarchar(10));
insert into @TableA values('Rec1'),('Rec2'),('Rec3');

declare @QueryResult table(TableA nvarchar(10),TableB nvarchar(10));
insert into @QueryResult values('Rec1','String1'),('Rec1','String2'),('Rec2','String1'),('Rec3','String1'),('Rec3','String2'),('Rec3','String3');


select TableA
        ,stuff((select ', ' + TableB  -- The ', ' is the delimiter.  The first instance of this is removed by the STUFF function.
                from @QueryResult t2
                where t1.TableA = t2.TableA
                order by t2.TableB
                for xml path('')
               )
              ,1,2,''                 -- This is where you specify how much from the start to remove.  
              ) as TableB
from @TableA t1;

输出:

+--------+---------------------------+
| TableA |          TableB           |
+--------+---------------------------+
| Rec1   | String1, String2          |
| Rec2   | String1                   |
| Rec3   | String1, String2, String3 |
+--------+---------------------------+

stuff函数从第一个参数值(在本例中为1)中指定的第n个字符开始,并将其替换为第二个参数位置中的字符(在这种情况下)字符2)带有您的第三个参数值(在本例中为空字符串'')。

这意味着上面for xml语句的正常输出对, String1, String2Rec1,但在应用stuff后,前两个字符将替换为一个空字符串,所以String,String2`结果。