Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何根据映射表选择列名?_Sql_Sql Server 2008 R2 - Fatal编程技术网

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

Sql 如何根据映射表选择列名?,sql,sql-server-2008-r2,Sql,Sql Server 2008 R2,嗨,我想做的是:我有两张桌子 第一个是 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

嗨,我想做的是:我有两张桌子 第一个是

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    |

哭吧。我是说,别这样!这将需要混乱的动态SQL,因为SQL标识符必须在执行时固定以保证“形状”。在客户端上使用数据时(例如,更改相关的.NET DataTable列标题名称),执行此转换可能更容易。或者,最好使用正确规范化的模式,即没有AreaX列。(实际上,在没有动态SQL的情况下,也可以使用,首先创建规范化的派生集,假设“Area Table”中的
列)仅限于一组固定的值,但不是我想探索/使用的东西。)我所说的“规范化模式”是指让模式看起来像:
personPersonarea
。具有“人员”关系和“区域”关系,然后在两者之间具有链接表(“PersonArea”)。规范化方法将使一般数据使用更容易,并允许在最后一步中使用PIVOT以实现预期结果。与前面的注释一样,PIVOT要求提供一组数据透视的列名,并且只有动态SQL可以在任意一组提供的列名上执行此操作:避免!
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