在变量声明中的情况

时间:2012-11-07 13:09:27

标签: sql sql-server tsql

enter image description here

我正在寻找另一个列,该列将显示eduCounts列旁边每个性别的总计数。查询的其余部分工作正常。在这种情况下查找不同的性别计数必须由select count(distinct patid) from...

完成

首先尝试:

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

第二次尝试:

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

我知道我可以制作一个派生表并加入性别列,但我想知道如何尽可能地使用变量。

1 个答案:

答案 0 :(得分:1)

你的意思是:

select Sex, eduText, eduCounts, sum(eduCounts) over (Partition by Sex) from(
select Sex, eduText, count(eduText) eduCounts
From TableName group by Sex, eduText)x
相关问题