This is your table and data:
CREATE TABLE Test ( TaxTypeCode1 CHAR(4), TaxTypeCode2 CHAR(4), PNO INT, Amount INT ) INSERT INTO Test VALUES('TX01', 'TX02', 124, 600) INSERT INTO Test VALUES('TX02', null, 124, 700) INSERT INTO Test VALUES('TX03', 'TX04', 124, 200) INSERT INTO Test VALUES('TX04', null, 124, 300) INSERT INTO Test VALUES('TX05', 'TX06', 126, 400) INSERT INTO Test VALUES('TX06', null, 127,500) INSERT INTO Test VALUES('TX07', null, 128, 800)
and this is the request for you:
SELECT PNO, SUM(Amount) FROM Test GROUP BY PNO, COALESCE(TaxTypeCode2, TaxTypeCode1)
The result corresponds to the expected result.
I found what you really do is aggregate data using PNO and the second or first column (if the second is empty). COALESCE(TaxTypeCode2, TaxTypeCode1) will return non-empty first.
You can also use ISNULL(TaxTypeCode2, TaxTypeCode1) . COALESCE can have more than two parameters, such as COALESCE(TaxTypeCode3, TaxTypeCode2, TaxTypeCode1) .
See that:
SELECT COALESCE(TaxTypeCode2, TaxTypeCode1) as sumBy, * FROM Test