如何将列转换为行或Vica Versa

时间:2016-03-02 09:21:08

标签: sql sql-server pivot

我有两张桌子

学生:

         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 

2 个答案:

答案 0 :(得分:2)

好的,没有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 APPLYVALUES子句将主题名称的键值对组合作为键,将其列值作为值。

<强>结果

subject  total_marks    ObtainedMarks
-------------------------------------
 Maths     100         98
 Science   100         67
 English    75         53
 Hindi      75         58

答案 1 :(得分:1)

这是学校问题的一个问题,但是让你怀疑,你应该尝试UNPIVOT语法而不是PIVOT语法。

请参阅here

的MSDN文档

使用UNPIVOT后跟LEFT JOIN,查询应如下所示

select UP.Subject,Total_Marks, Obtained_Marks from 
    (   
        select 
            S.Name as Name, 
            S.Maths as Maths, 
            S.Science as Science, 
            S.English as English, 
            S.Hindi as Hindi 
        from Student S
        where S.Name like 'sonia'
    )source
UNPIVOT 
    (
    Obtained_Marks for Subject in (Maths,Science, English, Hindi)
    )UP

LEFT JOIN  Subject S
ON S.Subject=UP.Subject
用于架构的

INSERT个查询:

create table subject(subject varchar(10), total_marks int)
insert into subject values('Maths',100),('Science', 100),('English', 75),('Hindi', 75)
create table student(name varchar(100),class int,maths int, science int,english int,hindi int)
insert into student values
('sonia',2,98,67,53,58),
('vijay',7,89,68,45,51)