您好我想做的是:我有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 |
答案 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