简体   繁体   English

TSQL中nvarchar列上的交叉表/数据透视查询

[英]Crosstab/Pivot query in TSQL on nvarchar columns

I have a Table1: 我有一个Table1:

ID  Property
1   Name
2   City
3   Designation

and Table2: 和表2:

ID  RecordID  Table1ID  Value
1   1         1         David
2   1         2         Tokyo
3   2         1         Scott
4   2         3         Manager

The Table1ID of Table2 maps to Table1's ID. Table2的Table1ID映射到Table1的ID。 Now I wish to show the Table1 Property column values as column headers and have a result set in format like: 现在,我希望将Table1属性列的值显示为列标题,并以以下格式设置结果集:

RecordID     Name    City    Designation
1            David   Tokyo   NULL
2            Scott   NULL    Manager

What is the best/efficient way to achieve this in T-SQL considering that the number of records in Table1 (ie the columns in result set) can change and thus should be handled dynamically . 考虑到Table1中记录的数量(即结果集中的列)可以更改,因此应该动态处理,因此在T-SQL中实现此目标的最佳/有效方法是什么。

Although I tried PIVOT and CASE based queries, but have been struggling with both of them. 虽然我尝试了基于PIVOT和CASE的查询,但是一直都在为它们苦苦挣扎。 :( :(

Any help/guidance would be appreciated. 任何帮助/指导将不胜感激。

Thanks! 谢谢!

Update: 更新:
I've been able to create the dynamic query, but one thing which I am still not able to understand is why MAX has been used in the CASE statements. 我已经能够创建动态查询,但是我仍然无法理解的一件事是为什么在CASE语句中使用了MAX。 Kindly ignore my noobness. 请忽略我的笨蛋。

Use: 采用:

  SELECT t2.recordid,
         MAX(CASE WHEN t1.property = 'Name' THEN t2.value END) AS name,
         MAX(CASE WHEN t1.property = 'City' THEN t2.value END) AS city,
         MAX(CASE WHEN t1.property = 'Designation' THEN t2.value END) AS designation
    FROM TABLE2 t2
    JOIN TABLE1 t1 ON t1.id = t2.table1id
GROUP BY t2.recordid
ORDER BY t2.recordid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM