Reputation: 149
The code I used was:
SELECT
AccountFK,
CASE WHEN B.ContractType = 'Telecoms' Then B.TermFeeMethod END AS TelecomsTermMethod,
CASE WHEN B.ContractType = 'Broadband' Then B.TermFeeMethod END AS BroadbandTermMethod,
CASE WHEN B.ContractType = 'Mobile' Then B.TermFeeMethod END AS MobileTermMethod,
CASE WHEN B.ContractType = 'Water' Then B.TermFeeMethod END AS WaterTermMethod,
ROW_NUMBER () OVER (PARTITION BY B.AccountFK ,B.TermFeeMethod ORDER BY A.CreatedDate DESC) AS RowNo
FROM
CRM.Contract.TermFeeTransaction AS A
INNER JOIN ContractSnapshot AS B ON A.ContractFK = B.ContractID
WHERE
CAST(b.CreatedDate as date) between '20180101' and '20190812'
AND B.TermFeeMethod IS NOT NULL
AND ContractType IN
('Telecoms',
'Broadband',
'Mobile',
'Water')
and AccountFK = '12345'
The output I'm looking for would be only one row, however, I'm getting two rows instead. Does anybody know how to merge them into one?
Upvotes: 0
Views: 73
Reputation: 1269445
Use conditional aggregation:
SELECT AccountFK,
MAX(CASE WHEN B.ContractType = 'Telecoms' Then B.TermFeeMethod END) AS TelecomsTermMethod,
MAX(CASE WHEN B.ContractType = 'Broadband' Then B.TermFeeMethod END) AS BroadbandTermMethod,
MAX(CASE WHEN B.ContractType = 'Mobile' Then B.TermFeeMethod END) AS MobileTermMethod,
MAX(CASE WHEN B.ContractType = 'Water' Then B.TermFeeMethod END) AS WaterTermMethod,
ROW_NUMBER () OVER (PARTITION BY B.AccountFK ,B.TermFeeMethod ORDER BY A.CreatedDate DESC) AS RowNo
FROM CRM.Contract.TermFeeTransaction A JOIN
ContractSnapshot B
ON A.ContractFK = B.ContractID
WHERE CAST(b.CreatedDate as date) between '20180101' and '20190812' AND
B.TermFeeMethod IS NOT NULL AND
ContractType IN ('Telecoms', 'Broadband', 'Mobile', 'Water') AND
AccountFK = '12345'
GROUP BY AccountFK;
Note: A
and B
are really bad choices for table aliases. They are just arbitrary letters. You should use tft
and cs
instead -- these are abbreviations for the table names.
Upvotes: 4