我有两张 table
学生:
Name Class Maths Science English Hindi
Sonia 2 98 67 53 58
Vijay 7 89 68 45 51
Abhishek Mishra 6 87 89 52 53
Rupal 8 74 76 59 64
Gaurav 10 90 78 43 41
主题:
Subject Total_Marks
Maths 100
Science 100
English 75
Hindi 75
当我选择名称 sonia 时,它应该提供以下 SQL 输出:
Subject Total_Marks Obtained Marks
Maths 100 98
Science 100 67
English 75 53
Hindi 75 58
最佳答案
好的,不用 UNPIVOT
你也能达到想要的结果,就像这样 -
DECLARE @subject table (subject varchar(10), total_marks int)
DECLARE @student table (name varchar(100),class int,maths int, science int,english int,hindi int)
INSERT INTO @subject
VALUES ('Maths', 100), ('Science', 100), ('English', 75), ('Hindi', 75)
INSERT INTO @student
VALUES ('sonia', 2, 98, 67, 53, 58),
('vijay', 7, 89, 68, 45, 51)
SELECT ri.subject, ri.total_marks, le.val as ObtainedMarks FROM
(
SELECT name, class, t.sub, t.val FROM @student
CROSS APPLY (VALUES ('maths', maths), ('science', science), ('english', english), ('hindi', hindi)) AS t(sub, val)
) le
INNER JOIN
(
SELECT * FROM @subject
) ri
ON le.sub = ri.subject
WHERE le.name = 'sonia'
这里我使用了CROSS APPLY
和VALUES
子句来制作主题名称作为键、其列值作为值的键值对组合。
结果
subject total_marks ObtainedMarks
-------------------------------------
Maths 100 98
Science 100 67
English 75 53
Hindi 75 58
关于sql - 如何将列转换为行或反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742976/