如何根据映射表选择列名?

时间:2013-09-06 23:00:11

标签: sql sql-server-2008-r2

您好我想做的是:我有2张桌子  第一个是

Person Table
PID | Name | Surname | Area1 | Area2 | Area3 | OwnerID |
1   | John | Doe     |   5   |   6   |   8   |    1    |
2   | Jack | Danniel |   8   |   2   |   4   |    2    |

第二个是

Area Table
AID | Value | Name  | OwnerID |
1   |  Java | Area1 |    1    |
2   |  Orac | Area2 |    1    |
3   |  Delp | Area1 |    2    |
4   |  Css  | Area3 |    1    |

如果我想选择Owner1,我如何查询结果?

PID | Name | Surname | Java  | Orac  | Css   | OwnerID |
1   | John | Doe     |   5   |   6   |   8   |    1    |

1 个答案:

答案 0 :(得分:0)

WITH A AS (
   SELECT PID, Name Name1, Surname, Area, _Area, OwnerID OwnerID1
   from Person A
   unpivot (_Area FOR Area IN (Area1, Area2, Area3)) C
 )

 select PID, Name1, Surname, sum(Java) JAVA, sum(Orac) Orac, sum(CSS) CSS, OwnerID
 from A
 inner join Area B 
   on Area = B.Name
   and A.OwnerID1 = B.OwnerID
 pivot (sum(_Area) for Value in (JAVA, ORAC, CSS)) C
 where OwnerID1 = 1
 group by PID, Name1, Surname, OwnerID

SQL Fiddle