I have a query that retrieves all agents and thier modules, the result set will return 1 row per module.
SELECT
am.agentID AS agentid,
pa.agentDisplayName agentdisplayname,
m.ModuleName ModuleName
FROM
AgentModule AS am
JOIN primaryagent AS pa
ON am.agentID = pa.AgentID
JOIN Module AS m
ON am.ModuleID = m.ModuleID
WHERE
m. Active = 1
AND pa.groupID = 75
Dataset is return as below
agentid | agentdisplayname | modulename 94 | Agent1 | Module 1 94 | Agent1 | Module 2 94 | Agent1 | Module 3 23 | Agent1 | Module 2 23 | Agent1 | Module 3
I am trying to use the PIVOT function to return a table that looks more like
agentid | agentdisplayname | Module 1 | Module 2 | Module 3 |.. .. .. 94 | Agent1 | 1 | 1 | 1 23 | Agent2 | 0 | 1 | 1
There are a dynamic list of modules so I cannot hard code them in the query. I have tried PICOT but it seems to expect an aggregate function and not quite sure it is what I would need for this scenario.
You can add a extra column to you result and use min() on that column. The result will be
1ornull. Useisnullto get a0instead ofnull.If you want to build this dynamically you need to first do a query that returns the modules you have in the result and then you need to use that to build the dynamic statement. It is probably best for you to store the result from your query in a temp table and then use that table when you build your dynamic query.
Build and run the dynamic query using
#Tmp.