如何从初始查询的结果将多行合并为1列

时间:2017-03-14 14:28:18

标签: sql sql-server sql-server-2008 tsql

我有一个查询,其中我提取了一些例外的发票数据。当特定服务类型被招标时,我们注意到了一些盗窃行为。:

Select Username, Service, Time, invoice#
From Invoice_Tb
Where Service_Category = 'Service_Type1'

输出:

Username      Service      Time              Invoice#
Bob           Service1     3/1/17 4:30AM     1234
Bobby         Service2     3/1/17 5:30AM     1633
Jim           Service2     3/7/17 5:45AM     1894

我想做的是从" Invoice_Detail"中获取更多信息。表,基于我的第一个查询的结果。我们发现审核所有记录非常艰巨。所以,我想看看这些发票上还有哪些附加服务。

我正在寻找的输出示例:

Username      Service      Time              Invoice#    Other_Services
Bob           Service1     3/1/17 4:30AM     1234        Service1, sv7, sv8
Bobby         Service2     3/1/17 5:30AM     1633        Service2, sv9, sv5
Jim           Service2     3/7/17 5:45AM     1894        Service2, sv7, sv9

请注意,Invoice_Detail_Tb会列出单独订单项的详细信息 - 始终列出相同的发票#。

1 个答案:

答案 0 :(得分:1)

您可以加入两个表:

Select 
    a.Username, 
    a.Service, 
    a.Time, 
    a.invoice#,
    b.other_services
From Invoice_Tb a JOIN invoice_detail_tbl b
    ON a.invoice# = b.invoice#
Where Service_Category = 'Service_Type1'

如果“other_services”是其他查询的组合,您可以将其更改为:

Select 
    Username, 
    Service, 
    Time, 
    a invoice#,
    other_services = STUFF((SELECT ',' + b.service
      FROM invoice_detail_tbl b WHERE b.invoice# = a.invoice#
      FOR XML PATH(''), TYPE).value(',', 'NVARCHAR(MAX)'), 1, 1, '')
From Invoice_Tb a
Where Service_Category = 'Service_Type1'