2013-03-14 57 views
2

我有一个被称为SectionNames如因此,对如下根据表列动态合并两列或多列?

SectionID SectionCode  Subsection 
    1   xYz   Individual 
    2   xYz   Family 
    3   CYD   Friends 
    4   PCPO  level1 
    5   PCPO  level2 
    6   PCPO  level3

表。因此,将来我们可以为每个部分代码添加一个或多个子部分。

另外还有一张表,这是上面SectionNames表和Employee表的员工数据参考表。

ID EmployeeID SectionID Cost  
1   1    1 $200 
2   1    2 $300  
3   1    3 $40 
4   1    4 $10 
5   1    5 No Level 
6   1    6 No Level 
7   1    7 $20 
8   1    8 No Level 
9   1    9 No Level

所以Iwant了出来,从这些表把应该是这样的:

EmployeeID  Individual_xyz_Cost Family_xyz_Cost Friends_xyz_cost level1_PCPO_cost level2_PCPO_Cost 
    1     $200     $300    $400    $10    NoLevel 

很少有员工记录存在于我的员工表。我希望这是动态的。如果将来如果为XYZ部分添加了另一个子部分Relatives,那么我的查询应返回Relatives_XYZ_Cost

如何动态地写这个查询?

回答

6

您将需要使用PIVOT函数将列中的数据转换为行。如果你将有一个未知数量的值需要是列,那么你将需要使用动态SQL。

首先查看静态或硬编码版本,然后将其转换为动态SQL版本更容易。

select * 
from 
(
    select e.employeeid, 
    s.subsection +'_'+s.sectioncode+'_Cost' Section, 
    e.cost 
    from employee e 
    inner join sectionnames s 
    on e.sectionid = s.sectionid 
) src 
pivot 
(
    max(cost) 
    for section in (Individual_xYz_Cost, Family_xYz_Cost, 
        Friends_CYD_Cost, level1_PCPO_Cost, 
        level2_PCPO_Cost, level3_PCPO_Cost) 
) piv; 

SQL Fiddle with Demo:当你有一个已知数值的静态版本使用。

如果您需要查询的是灵活的,那么你将其转换为使用动态SQL:

DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT ',' + QUOTENAME(subsection +'_'+sectioncode+'_Cost') 
        from SectionNames 
        group by subsection, sectioncode, sectionid 
        order by sectionid 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT employeeid,' + @cols + ' 
       from 
      (
       select e.employeeid, 
        s.subsection +''_''+s.sectioncode+''_Cost'' Section, 
        e.cost 
       from employee e 
       inner join sectionnames s 
        on e.sectionid = s.sectionid 
      ) x 
      pivot 
      (
       max(cost) 
       for section in (' + @cols + ') 
      ) p ' 

execute(@query) 

SQL Fiddle with Demo

共同作用的结果是:

| EMPLOYEEID | INDIVIDUAL_XYZ_COST | FAMILY_XYZ_COST | FRIENDS_CYD_COST | LEVEL1_PCPO_COST | LEVEL2_PCPO_COST | LEVEL3_PCPO_COST | 
---------------------------------------------------------------------------------------------------------------------------------- 
|   1 |    $200 |   $300 |    $40 |    $10 |   No Level |   No Level | 
+0

该作品像魅力......你是如此快速的人......感谢很多。 – user1882705 2013-03-14 16:31:07

+0

我可以如下使用这个动态结果集来加入一些其他表:内部连接(结果集)AS z ON z.ID = b.ID – user1882705 2013-03-14 18:10:31

+0

@ user1882705是的,你可以扩展sql字符串以将此select子查询 – Taryn 2013-03-14 18:18:14