0

我有下表:tb_answers

表结构如下

ID | QUESTIONID | SURVEYID | LEAGUEID | MEMBERID | ANSWER | DATEADDED | DIVISIONID

样本数据

302347 | 2336 | 172 | 146 | 68 | 467 Vallie Lane | 2012-05-21 16:36:22.433 | 0
302350 | 2340 | 172 | 146 | 68 | 591             | 2012-05-21 16:36:22.483 591

我需要按如下方式呈现这些数据。

DYNNAMIC LIST OF QUESTION#QUESTIONID# | MEMBERID | DIVISION
DYNNAMIC LIST OF VALUES OF QUESTION#QUESTIONID#|#MEMBERID#|DIVISION

所以我可以按值排序QUESTION#QUESTIONID#

这可能吗?我不擅长枢轴和联合,因此不胜感激。

4

1 回答 1

1

这是官方的 MS 示例:

SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days, 
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost 
    FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;

这是数据的一个支点:

USE AdventureWorks2008R2 ;
GO
SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost 
FROM Production.Product
GROUP BY DaysToManufacture;

产生这个

DaysToManufacture          AverageCost    
0                          5.0885    
1                          223.88    
2                          359.1082    
4                          949.4105

如您所见,他们明确指定了透视列 - 它不是数据驱动的。要使事情完全由数据驱动,您基本上必须执行两次,第一次将列名生成到字符串模板中。第二遍执行生成的 SQL。

DECLARE @dyncols AS VARCHAR(MAX) = (SELECT 
  STUFF((SELECT DISTINCT ',' + QUOTENAME(CONVERT(VARCHAR(50), YOURPIVOTCOL)) 
  FROM YOURTABLE FOR XML PATH(''), TYPE).VALUE('.', 'VARCHAR(MAX)'),1,1,''))
于 2013-03-28T00:35:03.980 回答