我有以下数据,我想透视并根据透视结果得到数字。T-SQL数据透视表数据透视结果
DECLARE @tempMusicSchoolStudent TABLE
(school VARCHAR(50),
studentname VARCHAR(50),
instrumentname VARCHAR(255),
expertise INT)
INSERT INTO @tempMusicSchoolStudent(school, studentname, instrumentname, expertise)
SELECT 'Foster','Matt','Guitar','10'
UNION
SELECT 'Foster','Jimmy','Guitar','5'
UNION
SELECT 'Foster','Jimmy','Keyboard','8'
UNION
SELECT 'Foster','Ryan','Keyboard','9'
UNION
SELECT 'Midlothean','Kyle','Keyboard','10'
UNION
SELECT 'Midlothean','Mary','Guitar','4'
UNION
SELECT 'Midlothean','Mary','Keyboard','7'
原始数据:
我想结果看起来像下面的数据....
我用得到这个数据下面的sql查询。这个查询的问题是我有一个动态数量的工具(为了简单起见,我在这个例子中只显示了2个)。我想使用数据透视表,因为它会更干净的动态SQL。否则,我必须动态地将每个乐器的表格自动加入到自己的表格中。
SELECT
t.school, t.instrumentname, t.expertise,
t1.instrumentname, t1.expertise,
COUNT(DISTINCT t.studentname) [DistinctStudentCount]
FROM
@tempMusicSchoolStudent t
LEFT JOIN
@tempMusicSchoolStudent t1 ON t1.school = t.school
AND t1.studentname = t.studentname
AND t.instrumentname <> t1.instrumentname
GROUP BY
t.school, t.instrumentname, t.expertise, t1.instrumentname, t1.expertise
ORDER BY
t.school, t.instrumentname, t.expertise, t1.instrumentname, t1.expertise
如果有人不是动态左侧的接合部表到它本身将不胜感激我如何能在一个更清洁的方式做到这一点的任何想法。谢谢。
你的输出中row1和row3有什么不同? – p2k
这里没有区别,但它是数据的预期模式。如果我可以删除那些很棒的重复,但现在用户可以很好地完成这些工作,因为他们希望完全连接数据。 – mgmedick