将普通查询转换为花式或分区/查询

时间:2012-10-19 02:24:45

标签: sql sql-server sql-server-2008 tsql

我的查询:

with cte as (
        select client_id,COUNT(patient_id) PatientCount from
        (
            select client_id,patient_id
            from F_ACCESSION_DAILY
            group by CLIENT_ID,PATIENT_ID
            having COUNT(ACCESSION_ID)=2
        ) a
        group by CLIENT_ID
)

有效,但对我没那么有用。因为虽然我可以轻松地加入此查询,但我实际上需要多次重复此WITH语句,因为我需要能够区分:

having count(Accession_id)=2

having count(Accession_id)=3

having count(accession_id)=4

依此类推,直到100左右

我想做更多这样的事情:

select distinct client_id, patient_id, count(*) over (partition by client_id, patient_id,accession_id) patientcount
    from f_accession_daily

但我被卡住了!

我想知道你是否可以指出我如何将初始查询转换成更有用的时候计算(加入)=许多不同的值

非常感谢你的指导。

1 个答案:

答案 0 :(得分:1)

像......一样的东西?

   select client_id,accessioncount,COUNT(patient_id) PatientCount from 
    ( 
        select client_id,patient_id, count(accession_id) as accessioncount
        from F_ACCESSION_DAILY 
        group by CLIENT_ID,PATIENT_ID 
    ) a 
    group by CLIENT_ID,accessioncount