0

enter image description here

I'm looking for another column that will give the overall total counts from each gender next to the eduCounts column. The rest of the query works fine. Finding the distinct gender counts in this case has to be done by select count(distinct patid) from...

first try:

declare @sexcounts int
set @sexcounts = case when members.sex 'm' then (select COUNT(distinct patid) from members where sex='m')
                 when members.sex 'f' then (select COUNT(distinct patid) from members where sex='f')

select sex, edutext, COUNT(*) as eduCounts from 
(
select distinct m.patid, m.sex, e.eduText
    from members as m
    inner join claims as c on c.patid=m.PATID
    inner join icdClm as ic on ic.clmid=c.clmid
    inner join tblICD as t on t.ICD=ic.icd
    inner join EducationTable as e on e.eduID=m.education
    inner join IncomeTable as i on i.incomeID=m.income
    where ISNUMERIC(ic.icd)=1 and SUBSTRING(ic.icd,1,3)='707'
)t
group by sex, eduText
order by sex

second try:

declare @sexcounts int
set @sexcounts = (select COUNT(distinct patid),case when sex 'm' then (select COUNT(distinct PATID) from members where sex='m') else (select COUNT(distinct patid) from members where sex='f') 
                    from members)

    select sex, edutext, COUNT(*) as eduCounts from 
    (
    select distinct m.patid, m.sex, e.eduText
        from members as m
        inner join claims as c on c.patid=m.PATID
        inner join icdClm as ic on ic.clmid=c.clmid
        inner join tblICD as t on t.ICD=ic.icd
        inner join EducationTable as e on e.eduID=m.education
        inner join IncomeTable as i on i.incomeID=m.income
        where ISNUMERIC(ic.icd)=1 and SUBSTRING(ic.icd,1,3)='707'
    )t
    group by sex, eduText
    order by sex

I know I could make a derived table and join on the sex column, but I'd like to know how to do it with a variable if at all possible.

4

1 回答 1

1

Do you mean this:

select Sex, eduText, eduCounts, sum(eduCounts) over (Partition by Sex) from(
select Sex, eduText, count(eduText) eduCounts
From TableName group by Sex, eduText)x
于 2012-11-07T13:32:59.107 回答