If you convert your labels to a column of data grouped on customerID and serviceCode, you can solve this with two intermediate results - one for the amounts grouped by CustomerID
and ServiceCode
, and one for the labels grouped by CustomerID
and ServiceCode
. With the labels, you have the added step of converting your "column" of values into a "list" of values, which is something that has been asked many times before I guess. There is more than one solution, and probably better ones if you have more recent versions of SQL Server. See this post: how-to-turn-one-column-of-a-table-into-a-csv-string-in-sql-server-without-using
Here is an example for your situation, but surely needs more data for testing, to make sure all your cases are accounted for. I suppose it goes without saying that you should normalize your data, and not have these fields such as Label_One, Label_Two, Label_Three ... etc., and then we would not need the long union
query to get all the labels together.
-- -------------------------------------------------
-- 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;