SQL Server 使用CONCAT?将行折叠成

xlpyo6sf  于 2023-01-20  发布在  其他
关注(0)|答案(1)|浏览(170)

我尝试了各种方法将这两行合并为一行,但似乎找不到正确的方法。我有数千行数据要处理,如果能找到解决方案,那就太好了。
到目前为止,我有这样的代码:

SELECT
    CustomerID
    , ServiceCode
    , CONCAT(LABEL_ONE, + ', ' + LABEL_TWO, + ', ' + LABEL_THREE, + ', ' + LABEL_FOUR) Labels
    , SUM(AMOUNT) TotalAmount
FROM Customer.dbo.Orders
GROUP BY
    CustomerID
    , ServiceCode
    , Labels

我得到的结果是这样的:
| 客户ID|服务代码|标签|总额|
| - ------|- ------|- ------|- ------|
| 小行星123456|小行星||一百七十二块三三|
| 小行星123456|小行星|HY、CFD|无|
我需要的是这个:
| 客户ID|服务代码|标签|总额|
| - ------|- ------|- ------|- ------|
| 小行星123456|小行星|HY、CFD|一百七十二块三三|

zbwhf8kr

zbwhf8kr1#

如果将标签转换为按customerID和serviceCode分组的数据列,则可以使用两个中间结果解决此问题-一个用于按CustomerIDServiceCode分组的金额,另一个用于按CustomerIDServiceCode分组的标签。使用标签,您还需要将值的“列”转换为值的“列表”。这是一个已经被问过很多次的问题。有不止一个解决方案,如果你有更新版本的SQL Server,可能会有更好的解决方案。请看这篇文章:how-to-turn-one-column-of-a-table-into-a-csv-string-in-sql-server-without-using
下面是一个适合您的情况的示例,但肯定需要更多数据进行测试,以确保考虑到所有情况。我认为,不用说,您应该规范化数据,并且不使用Label_One、Label_Two、Label_Three等字段,这样我们就不需要长union查询来将所有标签放在一起。

-- -------------------------------------------------
-- Some Test Data
declare @Temp table (
    CustomerID int,
    ServiceCode int,
    Amount decimal(9, 2),
    Label_One nvarchar(30),
    Label_Two nvarchar(30),
    Label_Three nvarchar(30),
    Label_Four nvarchar(30)
);
insert into @Temp values
    (123456, 1066, 123.66, 'HY', 'CFD', null, null),
    (123456, 1066, 0.00, null, null, null, null)
-- -------------------------------------------------
-- -------------------------------------------------

-- Two CTEs representing the amounts by service code and customer,
-- and the labels by service code and customer
-- (think of these as two temp tables if you are not familiar with CTEs)
;with amounts as (
    select
        CustomerID,
        ServiceCode,
        sum(Amount) TotalAmount
    from
        @Temp
    group by
        CustomerID,
        ServiceCode
),
labels as (
    select
        CustomerID,
        ServiceCode,
        Label_One as [Label]
    from @Temp
    union all
    select
        CustomerID,
        ServiceCode,
        Label_Two as [Label]
    from @Temp
    union all
    select
        CustomerID,
        ServiceCode,
        Label_Three as [Label]
    from @Temp
    union all
    select
        CustomerID,
        ServiceCode,
        Label_Four as [Label]
    from @Temp)

-- join the two CTEs on service code and customer,
-- with a "column to csv list" strategy for the labels.
select 
    amounts.CustomerID,
    amounts.ServiceCode,
    substring(
        (select ',' + labels.[Label]
        from labels labels
        where labels.CustomerID = amounts.CustomerID
            and labels.ServiceCode = amounts.ServiceCode
        order by labels.[Label]
        for xml path('')),2,200000
    ) as CSVList,
    amounts.TotalAmount
from 
    amounts;

相关问题