我有一个具有此架构的表:
tbl结果
Question1 | Question2 | Question3 | etc | etc | Question240 |
在这些列中,值可以是以下内容:
1, 2, 3, 4, N, M
我需要像这样呈现数据:
| QuestionNumber | 1 | 2 | 3 | 4 | N | M |
------------------------------------------
| Question1 | 53| 27| 10| 5 | 2 | 3 |
| etc | 20| 40| 32| 8 | 0 | 0 | <-- These values being % (but I can do the calculation later).
| etc |
我需要能够控制结果集将输出多少行。我通过执行以下操作(仅 3 列)完成了此操作:
DECLARE @cname VARCHAR(MAX)
SELECT @cname = STUFF((
SELECT ', ' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_NAME = 'tblResults') AND (ORDINAL_POSITION BETWEEN 8 AND 10)
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1,1,'')
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'SELECT Answers, CASE WHEN Answer = '''' THEN ''N'' ELSE Answer END AS Answer, COUNT(Answer) AS Total
FROM (
SELECT '+@cname+'
FROM tblResults
WHERE (something = ''006'') AND (somethingElse = ''ABC'')
) AS MyTable
UNPIVOT (Answer FOR Answers IN ('+@cname+')) AS MyUnPivot
GROUP BY Answers, Answer
ORDER BY Answers, Answer'
exec sp_executesql @sql
这会产生以下结果集:
| Answers | Answer | Total |
----------------------------
|Question1| 1 | 12474 |
|Question1| 2 | 188 |
|Question1| 3 | 200 |
|Question1| 4 | 5 |
|Question1| N | 0 |
|Question1| M | 142 |
|Question2| 1 | 14521 |
|etc | | |
|etc | | |
因此我的计划是使用动态 SQL,因为我想不出任何其他方法来做到这一点。我尝试了各种 UNPIVOT 方法,但似乎无法取得任何进展。
Beofre 任何人都建议这是一个多么糟糕的设计,我知道,这是我继承的东西,如果不重写第 3 方应用程序就无法更改它。
如果有人能想到更好的标题,请编辑。
谢谢。