I have a table like this:
+--------------+--------------+--------------+
| userid | username | proxy |
+--------------+--------------+--------------+
| 1 | j.doe | |
| 2 | lechnerio | 1,4 |
| 3 | janedoe | 1 |
| 4 | mustermann | 2 |
+--------------+--------------+--------------+
The proxy can either be NULL, one or more IDs from other users.
I'd like to build a view that helps to visualize the user. I thought of a similar result like this:
+--------------+--------------+--------------+-----------------------------+
| userid | username | proxy | proxy_info |
+--------------+--------------+--------------+-----------------------------+
| 1 | j.doe | | |
| 2 | lechnerio | 1,4 | j.doe (1), mustermann (4) |
| 3 | janedoe | 1 | j.doe (1) |
| 4 | mustermann | 2 | lechnerio (2) |
+--------------+--------------+--------------+-----------------------------+
I can't wrap my head around the sub-select I need for the proxy_info. The table itself has more than these three columns, but that shouldn't matter in this example. combining the proxy_info with a username and the id in brackets isn't the issue either. Yet I'm unable to subselect the values where the userid matches.
I'd be happy about any tips and hints to achieve the result listed above.
I thought about either joining the table with itself or using a union. But both options seem over-complicated for the desired result. I'm working with SQL Server here.
as of an idea:
SELECT a.agentcode
,a.username
,a.proxy
,(
SELECT b.agentcode
FROM app_users b
WHERE a.agentcode = b.proxy
) AS proxy_info
FROM app_users a