Report statistics (SQL interview questions)

Source: Internet
Author: User

This article from: http://www.cnblogs.com/xiaopin/archive/2010/08/20/1804699.html

There are three tables:

Student table: S

Field: Student ID, Student name

 

Course schedule: c

Field: course No. Course name

 

Orders table: SC

Field: Student ID, course number, score

 

The final result is as follows:

(Some courses are omitted later)

 

Implementation Method:

Method 1:

Selectmax (S. [name]) as name, max (casewhen SC. cid = '1' then SC. score end) as English, max (casewhen SC. cid = '2' then SC. score end) as Chinese, max (casewhen SC. cid = '3' then SC. score end) as history --... of course, the number of such items can be as follows, but SC. the Cid value must be consistent with the course ID in table C, and the alias must also be consistent with the course name from SC, s where SC. SID = S. id groupby SC. sid go

 

The running result is shown in the previous figure.

Advantage: This method is a bit silly and easy to understand.

Disadvantage: all are fixed. If the demand changes, you need to change the code.

 

Method 2: Declare @ sqlvarchar (8000) set @ SQL = ''select @ SQL = @ SQL + ', max (case when SC. cid = ''' + convert (varchar, SC. CID) + ''' then SC. score end) ['+ convert (varchar, C. [name]) + ']' from SC, C where SC. cid = C. id groupby SC. CID, C. [name] Set @ SQL = stuff (@ SQL, 1, 1, '') print @ sqlexec ('select max (S. [name]) as [name], '+ @ SQL +' from SC, s where SC. SID = S. id group by SC. sid ')

 

Running result:

Here we find that the score of chemistry is not? The reason is that there is no score record for chemistry in the transcript.

In this way, a dynamic REPORT query is realized.

 

 

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.