我有以下情况: 我有2列,第一列称为AgentID,第二列在代理表中称为AgentName。很少有AgentID以" A"很少开始使用" M",我想要做的是以下内容:
AgentID AgentName
A123 Name1
M123 Name2
A234 Name3
Aagents AAgentName Magents MAgentName
A123 Name1 M123 Name2
A234 Name3 NULL NULL
这可能吗?我知道这很奇怪,但我的老板希望这样做!
答案 0 :(得分:1)
您可以在2个子查询之间进行完全外部联接(一个用于A代理,一个用于M个代理),并且在ROW_NUMBER()
上加入以在一侧具有空值(具有较少记录的那个):
select A.AgentID Aagents, A.AgentName AAgentName, M.AgentID Magents, M.AgentName MAgentName from
(select *, ROW_NUMBER() over (order by AgentID) rn from Agents where AgentID like 'A%') A
full outer join
(select *, ROW_NUMBER() over (order by AgentID) rn from Agents where AgentID like 'M%') M
on A.rn = M.rn
答案 1 :(得分:1)
试试这个
WITH AAgents AS
(
SELECT ROW_NUMBER() over (order by AgentID) AS RN,
AgentID AS Aagents,
AgentName As AAgentName
FROM Agents
WHERE LEFT(AgentID,1)='A'
),
MAgents As
(
SELECT ROW_NUMBER() over (order by AgentID) AS RN,
AgentID AS Magents,
AgentName As MAgentName
FROM Agents
WHERE LEFT(AgentID,1)='M'
)
SELECT
Aagents,
AAgentName,
Magents,
MAgentName
FROM AAgents
FULL OUTER JOIN MAgents
ON AAgents.RN=MAgents.RN
答案 2 :(得分:0)
尝试这个
select * from (select AgentID as Aagents, AgentName as AagentName from table where
AgentID like 'A%'), (select AgentID as MAgents, AgentName as MAgentName from
table where AgentID like 'M%')
答案 3 :(得分:0)
类似的东西:
select
case when AgentName like 'A%' then name end as Aagents,
case when AgentName like 'M%' then Name end as Magents
from tblName