Tips for calculating the value of a specific segment in SQL

Source: Internet
Author: User

I am helping customers with some statistics today. I need to make statistics based on a specific area. So I searched the internet and found no satisfactory results, the closest is the http://bbs.csdn.net/topics/70184424 7 floor of the answer, but this statistics can not specify the segment, so I figured out, wrote such a statement:

Declare @ tb table (id int identity (1, 1), num int)

Insert into @ tb (num) values (1), (10), (20), (25), (12), (15), (13), (22 ), (5), (50), (80), (110)

Select count (*), overall, over10, over20, over50, over100 from (select 1 as overall, convert (bit, num/10) as over10, convert (bit, num/20) as over20, convert (bit, num/50) as over50, convert (bit, num/100) as over100 from @ tb) as a group by overall, over10, over20, over50, over100

I perform a ratio based on each specified segment and convert it to the bit type. In this way, the result is either 1 that meets the condition or 0 that does not meet the condition, then you can get the result in the entire group.

Of course, I didn't include the statistical section in SQL, So I modified the SQL command.

Declare @ tb table (id int identity (1, 1), num int)

Insert into @ tb (num) values (1), (10), (20), (25), (12), (15), (13), (22 ), (5), (50), (80), (110)

Select N 'scope '= (case (overall + over10 + over20 + over50 + over100) when 1 then '0-9' when 2 then '10-19 'when 3 then' 20-49 'when 4 then' 50-99 'else' 100 + 'end ), count (*) from (select 1 as overall, convert (bit, num/10) as over10, convert (bit, num/20) as over20, convert (bit, num/50) as over50, convert (bit, num/100) as over100 from @ tb) as a group by (overall + over10 + over20 + over50 + over100)

In this way, we can get the Section statistics we need.

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.