我有以下表格:
+------+--------------+------------+--------+
| ID | TestID | QuestionId | Answer |
+------+--------------+------------+--------+
| 1 | 10 | 15 | 0 |
| 2 | 10 | 23 | 0 |
| 3 | 10 | 41 | 1 |
| 4 | 16 | 15 | 0 |
| 5 | 16 | 23 | 1 |
| 6 | 16 | 41 | 1 |
| 7 | 24 | 15 | 1 |
| 8 | 24 | 23 | 0 |
| 9 | 24 | 41 | 0 |
+------+--------------+------------+--------+
对于内部报告,我需要以下输出:
+--------------+----------------+----------------+----------------+
| QuestionId | Test_1 | Test_2 | Test_3 |
+--------------+----------------+----------------+----------------+
| 15 | 0 | 0 | 1 |
| 23 | 0 | 1 | 0 |
| 41 | 1 | 1 | 0 |
+--------------+----------------+----------------+----------------+
我不知道该怎么做。 你有什么建议吗?
答案 0 :(得分:3)
使用Pivot
;WITH CTE
AS
(
SELECT
SeqNo = ROW_NUMBER() OVER(PARTITION BY QuestionId ORDER BY TestId),
*
FROM YourTable
)
SELECT
QuestionId,
Test_1 = MAX([1]),
Test_2 = MAX([2]),
Test_3 = MAX([3])
FROM CTE
PIVOT
(
SUM(Answer)
FOR SeqNo in
(
[1],[2],[3]
)
)P
GROUP BY QuestionId
我的结果
答案 1 :(得分:1)
这是使用条件聚合和Row_number
窗口函数
select QuestionId,
Test_1 = max(case when rn = 1 then Answer end),
Test_2 = max(case when rn = 2 then Answer end),
Test_3 = max(case when rn = 3 then Answer end)
from (select *, Rn = row_number()over(partition by QuestionId order by TestID)
from table1) a
group by QuestionId
如果测试的数量未知,那么你必须使用动态sql
答案 2 :(得分:1)
一个想法:
USE Sandbox;
GO
CREATE TABLE #Test (ID int, TestID int, QuestionID int, Answer tinyint);
INSERT INTO #Test
VALUES (1,10,15,0),
(2,10,23,0),
(3,10,41,1),
(4,16,15,0),
(5,16,23,1),
(6,16,41,1),
(7,24,15,1),
(8,24,23,0),
(9,24,41,0);
GO
WITH Rnks AS (
SELECT *,
DENSE_RANK() OVER (ORDER BY TestID) AS TestNum
FROM #Test T)
SELECT QuestionID,
MAX(CASE WHEN TestNum = 1 THEN Answer END) AS Test_1,
MAX(CASE WHEN TestNum = 2 THEN Answer END) AS Test_2,
MAX(CASE WHEN TestNum = 3 THEN Answer END) AS Test_3
FROM Rnks
GROUP BY QuestionID;
GO
DROP TABLE #Test;
然而,这假设测试数量有限(我已经猜到了test_ x 的正确定义)。如果您有不确定数量的测试,则需要使用动态SQL。