Query in statistical reports

Source: Internet
Author: User

The table data structure is as follows:

No class sex
01001 Grade 3 male
Third-grade female 01002
Third-grade female 01003
01004 Grade 4 male
01005 Grade 4 male
Fifth-grade female
01007 sixth-grade female

The following result set is displayed:

Grade male count
Grade 1 2 3
Grade 2 0 2
Fifth grade 0 1 1
Sixth grade 0 1 1 1
Total 3 4 7

 

 Select Class,Sum ( Case   When Sex =  '  Male  '   Then   1   Else   0   End  ),  Sum ( Case   When Sex=  '  Female  '   Then   1   Else   0   End  )  From A Group   By Class

 

This is very simple, but the trouble is that sex is not fixed, that is to say, there may also be a demon, and other unfixed gender fields.

So we need to use a loop, so we need to use a cursor. First we need to find all the sex fields. Then, the cursor is used to traverse the result set and concatenate strings cyclically.

 Declare  @ Sex   Varchar ( 50  )  Declare   @ SQL   Varchar ( 500  )  Set   @ SQL  =  '  Select class,  '  Declare MycursorCursor   For   Select Sex From Test Group   By  Sex  Open Mycursor Fetch   Next   From Mycursor Into   @ Sex  While ( @ Fetch_status =  0  )  Begin  If ( @ Sex  =  ''   Or   @ Sex  =  Null  )  Set   @ Sex  =  '  Not Configured '  Set   @ SQL  + =  '  Sum (case when sex =  '''  +  @ Sex  +  '''  Then 1 else 0 end)  '  +  @ Sex  +  '  , '  Fetch   Next   From Mycursor Into   @ Sex  End  Close Mycursor Deallocate  Mycursor  Select   @ SQL  =  Substring ( @ SQL , 1 , Len ( Ltrim ( Rtrim ( @ SQL ))) -  1  )  Set   @ SQL  + =  '  From test group by class  '  Exec ( @ SQL )

 

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.