不要以为我找到了这个特定的解决方案 - 如果有的话,我很抱歉搜索技巧不好!
我有一个单独的学生注册表,我被要求制作一个带有双重入口矩阵的报告,其中包含一对共享学生注册的课程单元(我的描述很混乱所以我会说明):< / p>
原始表:
预期结果:
这可能/可行吗?
原始表是一个简单的2列表,其中包含学生 - 单位 - http://pastebin.com/RfHYHK91
答案 0 :(得分:0)
这就是使用学生ID的COUNT()看起来像PIVOT的样子......但是我无法弄清楚你是如何计算你的价值的 - 例如,A / C十字架应该是2 (?)不是1,等等......:
DECLARE @student TABLE (unit VARCHAR(1), student INT)
INSERT INTO @student SELECT 'A',1
INSERT INTO @student SELECT 'A',2
INSERT INTO @student SELECT 'A',3
INSERT INTO @student SELECT 'B',1
INSERT INTO @student SELECT 'B',2
INSERT INTO @student SELECT 'C',1
INSERT INTO @student SELECT 'C',3
INSERT INTO @student SELECT 'D',4
SELECT unit, [A] AS A,[B] AS B, [C] AS C,[D] AS D
FROM
(SELECT unit, unit AS u, student FROM @student) AS S
PIVOT
(
COUNT(student)
FOR u IN([A],[B],[C],[D])
) AS P;
答案 1 :(得分:0)
这是一个看起来(几乎)完全像你想要的输出的输出(不是一个非常有用的方法,如果你需要添加/删除单位,因为每次都需要手动操作):
DECLARE @student TABLE (unit VARCHAR(1), student INT)
INSERT INTO @student SELECT 'A',1
INSERT INTO @student SELECT 'A',2
INSERT INTO @student SELECT 'A',3
INSERT INTO @student SELECT 'B',1
INSERT INTO @student SELECT 'B',2
INSERT INTO @student SELECT 'C',1
INSERT INTO @student SELECT 'C',3
INSERT INTO @student SELECT 'D',4
SELECT 'A','-' AS A, '' AS B, '' AS C, '' AS D
UNION
SELECT 'B',CONVERT(VARCHAR,COUNT(a.student)) AS A, '-' AS B, '' AS C, '' AS D FROM @student A INNER JOIN @student B ON A.student = B.student AND A.unit = 'A' AND B.unit = 'B'
UNION
SELECT 'C',CONVERT(VARCHAR,COUNT(a.student)), CONVERT(VARCHAR,COUNT(b.student)), '-','' FROM @student A INNER JOIN @student C ON A.student = C.student AND A.unit = 'A' AND C.unit = 'C' LEFT JOIN @student B ON B.student = C.student AND B.unit = 'B' AND C.unit = 'C'
UNION
SELECT 'D',CONVERT(VARCHAR,COUNT(a.student)), CONVERT(VARCHAR,COUNT(b.student)), CONVERT(VARCHAR,COUNT(c.student)),'-' FROM @student A INNER JOIN @student D ON A.student = D.student AND A.unit = 'A' AND D.unit = 'D' LEFT JOIN @student B ON B.student = D.student AND B.unit = 'B' AND D.unit = 'D' LEFT JOIN @student C ON D.student = C.student AND C.unit = 'C' AND D.unit = 'D'