CREATE TABLE Products
(
Customerkey int NOT NULL PRIMARY KEY,
processdate date NULL,
CCcount int NULL,
CHKcount int NULL,
SACount int NULL,
VEHCount int NULL,
LoanCount int NULL,
MortCount int NULL
);
INSERT INTO products (Customerkey, processdate, CCcount, CHKCount, SACount, VEHCount, LoanCount, MortCount)
VALUES (101, '20210501', 12, 3, 5, 1, 3, 1),
(102, '20210203', 1, 3, 1, 0, 0, 0),
(103, '20190412', 4, 0, 2, 0, 3, 1)
SELECT
Customerkey, processdate,
REPLACE(x.query('data(/root/*)').value('text()[1]', 'VARCHAR(100)'), SPACE(1), ',') AS Product_Mix,
REPLACE(x.query('for $x in /root/*[./text()!=""]
return local-name($x)').value('text()[1]', 'VARCHAR(100)'), SPACE(1), '+') AS Product_Mix_Expanded
FROM
@tbl
CROSS APPLY
(SELECT CCcount, CHKCount, SACount
FOR XML PATH(''), TYPE, ROOT('root')) AS t(x);
I want LoanProduct_Mix for these VEHCount, LoanCount, MortCount. This is from this link SQL Server 2016: how to get a single row view
Expected output:
| CustomerKey | processdate | Product_Mix | Product_Mix_Expanded | LoanProduct_Mix |
|---|---|---|---|---|
| 101 | 2021-05-01 | 12,3,5 | CCcount+CHKCount+SACount | VEHCount+LoanCount+MortCount |
| 102 | 2021-02-03 | 1,3,1 | CCcount+CHKCount+SACount | |
| 103 | 2019-04-12 | 4,0,2 | CCount + SACount | LoanCount + MortCount |