Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Select categorize by range

Author  Topic 

mike13
Posting Yak Master

219 Posts

Posted - 2014-05-15 : 12:23:35
Hi All

We have a table with order amounts and dates and need to sort and group them range values.
for a month.

There will be 6 ranges (increments of 40) : 0€ - 40€ / 41€ - 80€ / 81€ - 120€ / 121€ - 160€ / 161€ - 200€ / 200€ - 1000€

For example:
Customer total purchase = 39,55€ goes to range 0€ - 40€
Customer total purchase = 89,95€ goes to range 81€ - 120€

i'm trying to get a result that looks like

amount_orders, range
10, 0-40
14, 40-80

Thanks a lot

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2014-05-15 : 14:37:39
Here's one strategy:

with yourTable (dt, amt) as
(
select dateadd(day,-number,getdate())
,abs(convert(int, convert(varbinary, newid()))) / 10000000 --some random amount
from master..spt_values
where type = 'p'
and number < 100
)

select a as amount_orders
,case r
when 0 then '0-40'
when 40 then '41-80'
when 80 then '81-120'
when 120 then '121-160'
when 160 then '161-200'
else '>200'
end as [range]
from (
select count(*) a
,case when (amt/40)*40 > 200 then 200 else (amt/40)*40 end r
from yourTable
group by case when (amt/40)*40 > 200 then 200 else (amt/40)*40 end
) d
order by r

OUTPUT:

amount_orders range
------------- -------
14 0-40
16 41-80
19 81-120
26 121-160
20 161-200
5 >200


Be One with the Optimizer
TG
Go to Top of Page

mike13
Posting Yak Master

219 Posts

Posted - 2014-05-19 : 04:52:37
Thanks that worked!
Go to Top of Page
   

- Advertisement -