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 2000 Forums
 Transact-SQL (2000)
 Aggregate Issues

Author  Topic 

elwoos
Master Smack Fu Yak Hacker

2052 Posts

Posted - 2008-04-11 : 09:28:11
I'm sure I should know the answer to this but it seems to be eluding me for some reason. I can blame the fact it's late on a friday if it helps.

We have a simple table (in SQL Server 2000) with a structure like this

ModeOfTravel | LocalIdentifier | Region
Car | 123456 | Yorkshire
walk | 123456 | Lancashire
car | 654321 | Cumbria
walk | 789789 | Cumbria
walk | 789789 | Cumbria

what I am trying to get out of this is the Total numbers grouped by region (and mode of travel) and the percentage of the grand total by the same grouping

i.e.
Region | Mode | Total | percentage
Yorkshire | car | 1 | 20
Lancashire | walk | 1 | 20
Cumbria | car | 1 | 20
Cumbria | walk | 2 | 40

I can get the totals, just with a normal group by and a count, it's the percentages I am having trouble with. I'm sure I am missing something blindingly obvious but I can't see what and google isn't helping.

Many thanks in advance

steve


-----------

ASCII and ye shall receive.

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2008-04-11 : 09:37:35
[code]declare @t table
(
ModeOfTravel varchar(50),
LocalIdentifier int,
Region varchar(50)
)

insert @t
select 'Car',123456, 'Yorkshire' union all
select 'walk',123456, 'Lancashire' union all
select 'car',654321, 'Cumbria' union all
select 'walk',789789, 'Cumbria' union all
select 'walk',789789, 'Cumbria'

select t1.region, t1.modeoftravel, t1.cnt, t1.cnt*1.0/t2.grn_total * 100 as perc
from
(
select region, modeoftravel, count(*) as cnt
from @t
group by region, modeoftravel
) t1
cross join
(select count(*) grn_total from @t) t2[/code]

EDIT: Please add appropriate check to handle DIVIDE BY ZERO error.

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

elwoos
Master Smack Fu Yak Hacker

2052 Posts

Posted - 2008-04-11 : 09:47:41
Harsh you are a star many thanks

steve

-----------

ASCII and ye shall receive.
Go to Top of Page

RyanRandall
Master Smack Fu Yak Hacker

1074 Posts

Posted - 2008-04-11 : 09:51:06
Here's an alternative...

select
region, modeoftravel, count(*) as cnt,
100.0 * count(*) / (select count(*) grn_total from @t) as cnt
from @t
group by region, modeoftravel


Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
Go to Top of Page
   

- Advertisement -