I have a very simple query that I need pivoted, but I haven't got a clue how to turn it into a pivot table from what I've read in the literature. Everything I've read involves hard-coded columns or is too complex. It has to be simpler, or I just can't grasp CTE's.
The query is a list of user names and clients they have access to. So I have something like:
user client
1 a
1 b
1 c
2 a
2 d
3 a
3 d
3 e
3 f
The total number of clients could be around 20 or so. Some users can access all clients, others only one or two. What I want to see is:
user a b c d e f
1 x x x
2 x x
3 x x x x
This involves three tables: a user table, a client table, and a cross-reference table (permissions) that unites users with their clients.
I've tried something like the following, but it obviously doesn't work (or even compile).
with usersclients(user_name, clients, client_code)
as
(
select users.user_name
from clients cli
left join
(select u.user_id, user_name, c.client_id, client_code, client_name
from permissions p inner join clients c on p.client_id = c.client_id
inner join users u on u.user_id = p.user_id
) user
on user.client_id = cli.client_id
)
select *
from usersclients
pivot (max(client_code) for client_code in (select client_code from clients)) as P
Any clues most appreciated!