0

これらの値を持つテーブルがあります:

Empcode - Name - Skill - Primary
--------------------------------    
  1         X     .net    Yes
  1         X     c#  
  1         X     java   
  1         X     jsp
  2         Y     php     yes

データを次のように表示するSQLクエリを作成する必要があります

EmpCode  Name   PrimarySkill SecondarySkill
---------------------------------------------
   1     X      .net         c#,Java,jsp
   2     Y      Php

このクエリの生成にご協力ください。合体を試みましたが、機能しません

4

4 に答える 4

0
SELECT 
    Empcode, Name, 
    GROUP_CONCAT(Skill) 
FROM <table_name> 
GROUP BY Empcode 
ORDER BY Primary DESC
于 2013-01-25T10:43:31.793 に答える
0

これを試して、
SELECT distinct e.empcode, e.name ,
STUFF(( select ',' + t1.Skill from Employee t1
where t1.empcode = e.empcode and t1.name = e.name
for xml path('') ), 1, 1, '')' from Employee e

于 2013-01-25T12:17:28.757 に答える
0

FOR XML PATH を使用します。あなたの場合、それはこのようなものになります

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
于 2013-01-25T11:01:25.070 に答える
0

再帰的 CTE はこれを行うのに役立ちます

-- 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'
于 2013-01-25T11:05:13.123 に答える