Scenario: I have a table which returns markets where my fruit CAN NOT be sold. There can be up to 4 different conditions which exclude a market from fruit.
My code is:
SELECT DISTINCT RPin, Variety, SubDivisionId, BlockId , STUFF(( SELECT ',' + CAST(ClearanceID as varchar) FROM [RPin_ExclusionT] t1 where t1.RPin = t2.RPin AND t1.Variety = t2.Variety AND t1.SubDivisionId = t2.SubDivisionId AND t1.BlockId = t2.BlockId order by t1.ClearanceID FOR XML PATH('') ), 1, 1, '') AS Clearance FROM [RPin_ExclusionT] t2 For example:
Rpin Variety Subdivision Block Clearance 1234 039 B A RUS 1234 039 B A CHN Would result in:
Rpin Variety Subdivision Block Clearance 1234 039 B A RUS, CHN My code works if every field has data..Sometimes, a clearance may only have an RPin with everything else a NULL
Rpin Variety Subdivision Block Clearance 1234 039 B A RUS 1234 039 B A CHN 1234 NULL NULL NULL JAP 1234 NULL NULL NULL TWN I was this to return the same results, as before
Rpin Variety Subdivision Block Clearance 1234 039 B A RUS, CHN 1234 NULL NULL NULL JAP, TWN However, anywhere there is a NULL value in any column results in a NULL value in my clearance column.
Rpin Variety Subdivision Block Clearance 1234 039 B A RUS, CHN 1234 NULL NULL NULL NULL I'm intermediate at best with SQL and can't quite adjust the query to do as above ... any pointers would be greatly appreciated.