An SQL query

Juan Pablo González

MrExcel MVP
Joined
Feb 8, 2002
Messages
11,959
Ok... using SQL server, I need to make a 'simple' grouping query. I just need to count the number of customers, and graphing it by credit score, in ranges (less than 400, 400 - 500, 500 - 600, etc.). So I have this:

Code:
SELECT CASE
 WHEN RF_2 <= 400 THEN '<= 400'
 WHEN RF_2 <= 500 THEN '401 - 500'
 WHEN RF_2 <= 600 THEN '501 - 600'
 WHEN RF_2 <= 700 THEN '601 - 700'
 WHEN RF_2 <= 800 THEN '701 - 800'
 ELSE '> 800'

END 'Credit Score', COUNT(*) FROM TheTable

GROUP BY RF_2

which I thought was going to work, but nope... I get each record, well, except when the credit score is *exactly* the same in two or more different customers. So I thought, ok, change the 'Group' clause to

GROUP BY 'Credit Score'

but that says that 'GROUP BY expressions must refer to column names that appear in the select list.'

Any ideas ? I just want the query to return

Code:
<= 400       	20
401 - 500   	30
501 - 600   	35
601 - 700   	25
701 - 800   	15
> 800       	10
 

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop
Ok, if someone needs to know how I did it...

Code:
SELECT     Region, COUNT(*) Total
FROM 
 (SELECT 
  CASE 
  WHEN RF_2 <= 400 THEN '<= 400' 
  WHEN RF_2 <= 500 THEN '401 - 500' 
  WHEN RF_2 <= 600 THEN '501 - 600' 
  WHEN RF_2 <= 700 THEN '601 - 700' 
  WHEN RF_2 <= 800 THEN '701 - 800' 
  ELSE '> 800' END AS Region
  FROM TheTable) 
AS Derive(Region)
GROUP BY Region
 
Upvote 0

Forum statistics

Threads
1,223,275
Messages
6,171,126
Members
452,381
Latest member
Nova88

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top