年龄组查询但不同类型的分组

时间:2016-12-11 04:18:27

标签: sql sql-server

我有以下查询:

Declare @StartDate datetime
Set @StartDate = '2016-12-11 14:53:16.770'

select 
DrugName,
AgeGroup,
count(*) as Clients
from
(select 
D.DrugName,
case
when datediff(d,DOB,@StartDate) / 365.25 > 64 then '65 & over'
when datediff(d,DOB,@StartDate) / 365.25 > 54 then '55-64'
when datediff(d,DOB,@StartDate) / 365.25 > 44 then '45-54'
when datediff(d,DOB,@StartDate) / 365.25 > 34 then '35-44'
when datediff(d,DOB,@StartDate) / 365.25 > 24 then '25-34'
when datediff(d,DOB,@StartDate) / 365.25 > 18 then '19-24'
when datediff(d,DOB,@StartDate) / 365.25 > 12 then '13-18'
when datediff(d,DOB,@StartDate) / 365.25 > 0 then 'Below 12'
  end as AgeGroup
from Client C
Inner Join Visit V on C.ClientID = V.ClientID
Inner Join Drug D on V.DrugID = D.DrugID
) a
group by DrugName,AgeGroup
order by DrugName,AgeGroup

并返回所有DrugNames的正确结果分组并正确显示计数。

我也有这张表:

select * from AgeGroup

包含以下数据:

AgeGroupID  AgeGroup
1          65 & over
2          55-64
3          45-54
4          35-44
5          25-34
6          19-24
7          13-18
8          Below 12

我遇到的问题是我不确定如何显示每个药物名称的所有年龄组。

在可卡因的那一刻,我在上述查询中得到以下结果:

Cocaine 19-24       1
Cocaine 25-34       10
Cocaine 35-44       15
Cocaine 45-54       20
Cocaine 55-64       25
Cocaine 65 & over   30

但我想得到:

Cocaine Below 12    0
Cocaine 13-18       0
Cocaine 19-24       1
Cocaine 25-34       10
Cocaine 35-44       15
Cocaine 45-54       20
Cocaine 55-64       25
Cocaine 65 & over   30

同样适用于结果集中显示年龄范围缺失的所有其他药物。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

Declare @StartDate datetime
Set @StartDate = '2016-12-11 14:53:16.770'

;WITH cteAgeGroups AS (
    SELECT *
    FROM
       (VALUES (65,1000,'65 & over'),(55,64,'55-64'),(45,54,'45-54')
       ,(35,44,'35-44'),(25,34,'25-34'),(19,24,'19-24'),(13,18,'13-18')
       ,(0,12,'12 & Below')) t(StartRange,EndRange,AgeGroup)
)

SELECT
    a.AgeGroup
    ,d.DrugName
    ,COUNT(c.ClientId) as Clients
FROM
    cteAgeGroups a
    CROSS JOIN Drug d
    LEFT JOIN Visit v
    ON d.DrugId = v.DrugId
    LEFT JOIN Client c
    ON v.ClientId = c.ClientId
    AND (
       CASE
          WHEN
             (DATEADD(year,DATEDIFF(year, c.[DOB]  ,@StartDate) , c.[DOB]) > @StartDate)
          THEN DATEDIFF(year, c.[DOB]  ,@StartDate) -1
          ELSE DATEDIFF(year, c.[DOB]  ,@StartDate)
       END) BETWEEN a.StartRange AND a.EndRange
GROUP BY
    a.AgeGroup
    ,d.DrugName

答案 1 :(得分:0)

如果您需要两个表的所有组合,则需要使用CROSS JOIN

    SELECT * FROM DRUGS
     CROSS JOIN  AGEGROUP