首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用COALESCE串联值

使用COALESCE串联值
EN

Stack Overflow用户
提问于 2013-01-25 18:38:54
回答 4查看 241关注 0票数 0

我有一个包含以下值的表:

代码语言:javascript
运行
复制
Empcode - Name - Skill - Primary
--------------------------------    
  1         X     .net    Yes
  1         X     c#  
  1         X     java   
  1         X     jsp
  2         Y     php     yes

我必须编写一个SQL查询,它将数据显示为

代码语言:javascript
运行
复制
EmpCode  Name   PrimarySkill SecondarySkill
---------------------------------------------
   1     X      .net         c#,Java,jsp
   2     Y      Php

请帮助生成此查询。我尝试过coalesce,但不起作用。

EN

回答 4

Stack Overflow用户

发布于 2013-01-25 18:43:32

代码语言:javascript
运行
复制
SELECT 
    Empcode, Name, 
    GROUP_CONCAT(Skill) 
FROM <table_name> 
GROUP BY Empcode 
ORDER BY Primary DESC
票数 0
EN

Stack Overflow用户

发布于 2013-01-25 19:01:25

使用FOR XML路径。在您的情况下,应该是这样的

代码语言:javascript
运行
复制
SELECT  Empcode, Name, Skills
FROM   yourTable a
CROSS APPLY --or OUTER APPLY
(
    SELECT SUBSTRING(
        (SELECT ','+b.Skill FROM yourTable b
         WHERE   a.Empcode = b.Empcode FOR XML PATH(''))
    ,2 ,4000) Skills
) x
票数 0
EN

Stack Overflow用户

发布于 2013-01-25 19:05:13

递归CTE将帮助您做到这一点

代码语言:javascript
运行
复制
-- First order all the secondary skills with a row number
with rows as (
    select 
        empcode, skill, row_number() over (partition by empcode order by skill) as row
    from dbo.table_1
    where [primary] is null and skill is not null
),
-- Second use recursive CTE to create concat the values
cte(empcode,skill,row) as (

    select empcode, cast(skill as varchar(MAX)), row
    from rows where row=1
    union all
    select r.empcode, cast(concat(c.skill, ',', r.skill) as varchar(MAX)), r.row
    from
    cte c inner join rows r on r.row = c.row + 1
),
-- Third sort the resulting CTE so that can filter to only the end of 
--the recursive chain
ordered(empcode,skill,row) as (
    select empcode,skill, row_number() over (Partition by empcode order by row desc)
    from cte
)

-- Now fetch the results
select
    t.empcode,t.name, t.skill as [primary skill], o.skill as [secondary skill]
from
table_1 t
left outer join ordered o on t.empcode=o.empcode and o.row=1
where t.[Primary] = 'Yes'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14520078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档