我如何将表数据(多行)输出为多行连接的字符串

时间:2019-05-16 00:21:25

标签: sql concatenation ssms

我试图从使用2个表和group by ...的select语句构建的表数据中提取,然后将每行数据输出为一行连接文本。

我已经尝试尝试进行DECLARE,SET和打印为concat字符串。

use ap;

SELECT v.vendorid as 'VendorID', count(i.invoiceid) as 'Invoice Count', 
sum(i.invoicetotal) as 'Invoice Total' 
FROM vendors v
JOIN invoices i on i.vendorid = v.vendorid
GROUP BY v.vendorid

试图将其输出为...

供应商ID = 34发票计数2发票总数= 1,200.12

1 个答案:

答案 0 :(得分:4)

只需将其连接为字符串即可。您只需要将数字值转换为VARCHAR。

select 'VendorID = ' + CAST(v.vendorid AS VARCHAR(10)) + ' Count ' + CAST(count(i.invoiceid) AS VARCHAR(10)) +
    ' Invoice Totals = ' + FORMAT(sum(i.invoicetotal), 'c2')
from vendors v JOIN invoices i on i.vendorid = v.vendorid 
group by v.vendorid

使用此示例数据:

create table vendors (vendorid int)
create table invoices (vendorid int, invoiceid int, invoicetotal money)

insert into vendors values (34)
insert into invoices values (34, 1, 1000), (34, 2, 200.12)

返回:

VendorID = 34 Count 2 Invoice Totals = $1,200.12