【问题标题】:How can i output table data (multiple rows) as a multiple rows of concatenated strings如何将表数据(多行)输出为多行连接字符串
【发布时间】:2019-10-03 04:21:06
【问题描述】:

我正在尝试从使用 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

尝试像...一样输出它

VendorID = 34 发票计数 2 发票总数 = 1,200.12

【问题讨论】:

    标签: sql concatenation ssms


    【解决方案1】:

    只需将其连接成一个字符串。您只需要将数值转换为 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
    

    【讨论】:

    • 效果很好……我肯定是想多了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 2014-06-02
    • 2013-03-12
    • 2010-09-15
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多