How to do a SQL Query with Pivot

I have a lookup table and record batch Table I would like to do a count on the records stored in that batch by counting the number of records in that batch that have  a certain key on the responseKey column. This column keys are stored in the look up table for comparison. So I would like to do a join sql pivot that will use my keys stored in the lookup as columns and count as values

so far I have managed to do this but this is not efficient I would like to fire that sql once not on every count

SELECT * FROM
(
SELECT tMatch.DataValue, Count(*)
FROM ResponseRMAP.Record bRecord
JOIN Match ON tMatch.TableName = 'Match' AND tMatch.KeyName = bRecord.ResponseCode
WHERE bRecord.%ParentBatch = 55

)
 

Comments

I'm afraid we don't support the SQL PIVOT command, so unless you can enumerate the response codes as columns explicitly, you can only organise them as rows. If you control the application code, you could of course first have a query selecting all response codes and then generating the lengthy SQL call that includes separate columns for each response code. Something like SUM(CASE bRecord.ResponseCode WHEN 'response code 1' THEN 1 ELSE 0 END) AS ResponseCode1Count should work fairly well.