我试图从动态派生列中创建一个count case语句。基本上我想从每列知道学习目标值的计数< 3(数字不精通)和#34;熟练百分比" (学习目标值> 3 /动态派生列数,总是5)。
输出看起来像这样: ╔═══════════════════════╦══════╦══════╦══════╦════ ══╦══════╗ ║║8EE1║8EE2║8EE3║8EE4║8NS2║ ╠═══════════════════════╬══════╬══════╬══════╬════ ══╬══════╣ ║数字不精通║2║2║3║1║1║ ║百分比精通║50║50║25║75║75║ ╚═══════════════════════╩══════╩══════╩══════╩════ ══╩════════
CREATE TABLE temp1
(
stuid varchar(50),
learningObjective varchar(50),
numberCorrect int
)
INSERT INTO temp1 VALUES ('1315034576','8EE2', 5);
INSERT INTO temp1 VALUES ('1315034576','8EE3', 4);
INSERT INTO temp1 VALUES ('1315034576','8EE4', 3);
INSERT INTO temp1 VALUES ('1315034576','8NS2', 2);
INSERT INTO temp1 VALUES ('1315034576','8EE1', 1);
INSERT INTO temp1 VALUES ('1315036902','8EE2', 1);
INSERT INTO temp1 VALUES ('1315036902','8EE3', 2);
INSERT INTO temp1 VALUES ('1315036902','8EE4', 4);
INSERT INTO temp1 VALUES ('1315036902','8NS2', 5);
INSERT INTO temp1 VALUES ('1315036902','8EE1', 4);
INSERT INTO temp1 VALUES ('1315037112','8EE2', 2);
INSERT INTO temp1 VALUES ('1315037112','8EE3', 3);
INSERT INTO temp1 VALUES ('1315037112','8EE4', 5);
INSERT INTO temp1 VALUES ('1315037112','8NS2', 5);
INSERT INTO temp1 VALUES ('1315037112','8EE1', 5);
INSERT INTO temp1 VALUES ('1315042293','8EE2', 5);
INSERT INTO temp1 VALUES ('1315042293','8EE3', 2);
INSERT INTO temp1 VALUES ('1315042293','8EE4', 4);
INSERT INTO temp1 VALUES ('1315042293','8NS2', 5);
INSERT INTO temp1 VALUES ('1315042293','8EE1', 1);
这是我一直在研究的查询的精简版本。我以为我可以把逻辑放在枢轴部分但显然不会编译。
DECLARE @cols AS NVARCHAR(MAX)='', @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(learningObjective) + ','
FROM (select distinct learningObjective from temp1 where learningObjective <> 'Overall') as tmp
select @cols = substring(@cols, 0, len(@cols))
set @query =
'
SELECT ' + @cols +'
FROM
(
select temp1.STUID, learningObjective, numberCorrect
from temp1
INNER JOIN
(
select STUID
from temp1
)
z
ON temp1.STUID = z.STUID
) src
pivot
(
COUNT(case when numberCorrect < 4 then 1 end) for learningObjective in (' + @cols + ')
) piv
'
execute(@query)