Ok this coding piece - the TAT - may be simple for you but I am beating my head over this.
This returns the # of toys for each girl
Select Toys,
Count(Girls),
TAT
from Table1 (nolock)
ie
Girl Toys TAT
_____ ______ ___________
Kelly 1 0-5
Michelle 1 16-30
Grace 1 31+
Katy 1 6-10
Kelly 1 16-30
This returns the # of Toys in each age range
Select TAT,
Count(TAT)
from Table1 (nolock)
ie
TAT ??????
_____ ___________
0-5 1
6-10 0
11-15 1
16-30 2
31+ 1
The next step I need do is to divide 1 (Kelly for 16-30) by # of Toys in age range it was put in (2 for 16-30) :
1 / 2 = 50.00%
How do I do that? The column with the ???? is where I am stuck at.
Thank you! Holly
You sound really confused - out of the goodness of my heart, I took a stab at this. If this is not correct, you need to post more information on what exactly you need.
a. Your example queries are not correct (they will error due to missing GROUP BY
)
b. Your sample data is incomplete. In the first step, your data seems to indicate you want to group by Girl and TAT, but you explicitly say your query is counting toys per girl - not toys per Girl/TAT pair. Which is right?
"show the % of each toy(s) in each date range". This is not so simple when the sample data is incomplete
;WITH GirlTATCount AS (
SELECT
Girl,
TAT,
COUNT(*) as [ToyCount]
FROM Table1
GROUP BY Girl, TAT
)
, ToysInAgeRange AS (
SELECT
TAT,
COUNT(*) as [ToyCount]
FROM Table1
GROUP BY TAT
)
SELECT
gtc.Girl,
gtc.TAT,
gtc.ToyCount,
CAST(gtc.ToyCount as float) / CAST(tar.ToyCount as float) as [%]
FROM GirlTATCount gtc
JOIN ToysInAgeRange tar
ON tar.TAT = gtc.TAT
create table #table1 (Girl varchar(20), toys int, tat varchar(10))
insert into #table1 (Girl, toys, tat)
values ('Kelly',1,'0-5')
,('Michelle',1,'16-30')
,('Grace',1,'31+')
,('Katy',1,'6-10')
,('Kelly',1,'16-30')
declare @dividend numeric(5,2) = 1
;with gtcount as (select tat, COUNT(*) ctr
from #table1
group by tat )
select tat,ctr, @dividend/ctr percentage from gtcount
Hope this helps...
Elmer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.