SQL Query根据已解析的列连接两个表

时间:2015-08-12 14:15:35

标签: sql-server

我希望基于列加入输出,但问题是,其中一列被解析然后通过语句创建

PARSENAME(
   REPLACE(
      replace(
        replace(
          replace(
             replace(dbo.IDENTITY_MAP.Name,'My Company\',''),
          '-VLAN2','')
        ,'.VLAN2\','')
      ,'.Instr\','') 
  , '\' , '.')
,1)

输出

abc
123
abra
cadabra

另一个表的列直接打印为

abc
123
abra
cadabra

我试图解决这个问题:

abc      wine
123      sherry
abra     cognac
cadabra  whisky

和这个

abc       Alaska       Bobby
123       Canada       Jessie
abra      New Zealand  Audrey
cadabra   Maldives     Sammy

进入:

abc      wine    Alaska       Bobby
123      sherry  Canada       Jessie
abra     cognac  New Zealand  Audrey
cadabra  whisky  Maldives     Sammy

请记住,第一列其中一个表是使用PARSENAME

人工创建的

查询第一个输出

SELECT PARSENAME(REPLACE(replace(replace(replace(replace(dbo.IDENTITY_MAP.Name,'My Company\',''),'-VLAN2',''),'.VLAN2\',''),'.Instr\','') , '\' , '.'),1) as "Site",
                   Count (CASE
                            WHEN dbo.SEM_AGENT.AGENT_VERSION LIKE '11.%' THEN 1
                          END) AS 'SEP-11',
                   Count(CASE
                            WHEN dbo.SEM_AGENT.AGENT_VERSION LIKE '12.%' THEN 1
                          END) AS 'SEP-12'...
            FROM   dbo.sem_computer
                   INNER JOIN [dbo].[V_SEM_COMPUTER]
                           ON [dbo].[V_SEM_COMPUTER].COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID ...
            WHERE dbo.IDENTITY_MAP.Name NOT LIKE '%Servers%'
      Group by PARSENAME(REPLACE(replace(replace(replace(replace(dbo.IDENTITY_MAP.Name,'My Company\',''),'-VLAN2',''),'.VLAN2\',''),'.Instr\','') , '\' , '.'),1)
      Order by "Site" DESC

查询第二个输出

SELECT * from dbo.SEPM_Site

我创建了dbo.SEPM_Site,要加入的列实际上是主键!

enter image description here

1 个答案:

答案 0 :(得分:1)

如果我们在2005年之后谈论一个版本的sql server,为了对你所拥有的内容有所了解,你可以将查询放入CTE并将其与表格连接起来:

;with cte as (
  --- put the parsename query here (without the order by)
)
select 
  *  -- feel free to query what you need from here
from cte
join SEPM_Site ss
  on cte.Site = ss.Site