An analysis of SQL statements of query horizontal table variable vertical table in SQL Server _mssql

Source: Internet
Author: User
First is three tables, CNO corresponds to the course, where I pasted.

Primary table

Name list

Follow the general query

SELECT S.sname, C.cname,s2. Scgrade

From S INNER JOIN SC s2 on S2. SNo = S.sno INNER JOIN c c on c.cno = s2. CNo

So the result is this.

But this is not the result I want to see.

We want to see this result:

So what do we do?
The first method of writing:

Copy Code code as follows:

SELECT W.sname,
SUM (case when w.cno= 1 then w.scgrade ELSE 0) as ' language ',
SUM (case when W.cno =2 THEN w.scgrade ELSE 0) as ' math ',
SUM (case when w.cno= 3 then w.scgrade ELSE 0) as ' English '
From
(SELECT s.sno,s.sname, S2.) CNo, S2. Scgrade from S-INNER JOIN SC s2 on S2. SNo = S.sno WHERE s.sno in (SELECT C.sno to SC C GROUP by C.sno))
As W GROUP by W.sname
The second way:
Copy Code code as follows:

SELECT S.sname,
sum (case when S2.) cno= 1 then S2. Scgrade ELSE 0 end) as ' language ',
sum (case when S2.) CNo =2 THEN S2. Scgrade ELSE 0 end) as ' math ',
sum (case when S2.) cno= 3 then S2. Scgrade ELSE 0 end) as ' English '
From
s s INNER JOIN SC s2 on S2. SNo = S.sno
INNER JOIN c c on c.cno = s2. CNo
GROUP by S.sno,
S.sname

This is my work encountered situation, summed up. If you have encountered this situation, you can refer to the following.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.