SQL query statement (convert data tables from vertical to horizontal)

Source: Internet
Author: User

 

My table structure:
ID (primary key) studentno courseno score
1 01 2001 99
2 01 2002 98
3 01 2003 97
4 02 2001 95
5 02 2002 94
6 02 2003 93
-----------------------------------------------
Query Result
Studentno 2001 2002 2003
01 99 98 97
02 95 94 93
Declare @ s varchar (8000)
Set @ s = @ s + ', [' + Cast (courseno as varchar) + '] = sum (Case courseno when''' + Cast (courseno as varchar) + '''then score end )'
From table
Group by courseno
Exec ('select studentno' + @ s + 'from table group by studentno ')

Reproduced csdn: http://topic.csdn.net/t/20040611/09/3082327.html

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.