Question

I have the following code:

CREATE TABLE #table1
(
AgentID varchar(5),
AgentName varchar(50)
)

INSERT INTO #table1 VALUES ('A111A', 'Yes'), ('A111G', 'Yes'), ('A111M', 'Yes')

SELECT AgentID,
       CASE WHEN AgentID LIKE 'A%A' THEN AgentName END AS [A Agent],
       CASE WHEN AgentID LIKE 'A%G' THEN AgentName END AS [G Agent],
       CASE WHEN AgentID LIKE 'A%M' THEN AgentName END AS [M Agent]
 FROM #table1
DROP TABLE #table1

When I run the above code I get the following:

AgentID A Agent G Agent M Agent
A111A   Yes     NULL    NULL
A111G   NULL    Yes     NULL
A111M   NULL    NULL    Yes

I want to find a way to get the following result (Since the agent 111 has all Agent types):

 Agent   AAgent GAgent MAgent
 111     Yes    Yes    Yes
Was it helpful?

Solution

    SELECT SUBSTRING(AgentId,2,3) AS AgentID,
      MAX(CASE WHEN AgentID LIKE 'A%A' THEN 'Yes' ELSE 'No' END) AS [A Agent],
      MAX(CASE WHEN AgentID LIKE 'A%G' THEN 'Yes' ELSE 'No' END) AS [G Agent],
      MAX(CASE WHEN AgentID LIKE 'A%M' THEN 'Yes' ELSE 'No' END) AS [M Agent]
    FROM #table1
    GROUP BY SUBSTRING(AgentId,2,3)
    ORDER BY 1

OTHER TIPS

SELECT  SUBSTRING(AgentId,2,3),
        (SELECT CASE WHEN AgentID LIKE 'A%A' THEN AgentName END FROM #table1 WHERE AgentID = t1.AgentID) AS [A Agent],
        (SELECT CASE WHEN AgentID LIKE 'A%G' THEN AgentName END FROM #table1 WHERE AgentID = t1.AgentID)  AS [G Agent],
        (SELECT CASE WHEN AgentID LIKE 'A%M' THEN AgentName END FROM #table1 WHERE AgentID = t1.AgentID) AS [M Agent]
FROM #table1 t1
DROP TABLE #table1

You are better off using a table variable however, as those are only in memory and don't hit tempdb

DECLARE @my_temp_table TABLE
(
   myintcol int,
   myvarcharcol varchar(10)
)

INSERT INTO @my_temp_table (myintcol, myvarcharcol) VALUES(1,'some-text')

Assumption: Format of AgentID is always of the form A[0-9][0-9][0-9](A|G|M)

;with cte as
(select substring(agentid,2,3) id, count(agentname) count
 from #table1
 where agentname IS NOT NULL --Simply check that it is not null; values may not be identical
 group by substring(agentid,2,3)
 having count(*) = 3)

 select id as Agent, 'Yes' as AAgent, 'Yes' as GAgent, 'Yes' as MAgent from cte

Demo here.

To get actual agent names, use this query:

select distinct id as Agent
,(select agentname from #table1 t1 where substring(t1.agentid,2,3) = c.id and right(t1.agentid,1) = 'A') as AAgent
,(select agentname from #table1 t2 where substring(t2.agentid,2,3) = c.id and right(t2.agentid,1) = 'G') as GAgent
,(select agentname from #table1 t3 where substring(t3.agentid,2,3) = c.id and right(t3.agentid,1) = 'M') as MAgent
from cte c
inner join #table1 t on c.id = substring(t.agentid,2,3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top