3

我的数据如下所示:

+--------+-----------+---------+
| doctor | datefield | patient |
+--------+-----------+---------+
| A      | 1/1/2011  | ABC123  |
| A      | 1/20/2011 | AAA123  |
| A      | 1/21/2011 | AAA123  |
|        |           |         |
| A      | 2/1/2011  | ABC123  |
| A      | 2/10/2011 | BBBYYY  |
|        |           |         |
| B      | 1/1/2011  | ABC123  |
| B      | 1/20/2011 | AXA435  |
| B      | 1/21/2011 | AAA123  |
|        |           |         |
| B      | 2/1/2011  | ABC123  |
| B      | 2/10/2011 | BBBYYY  |
+--------+-----------+---------+

我想计算每个医生的新病人数as compared to the entire date range for that specific doctor

假设2011 年1 月是第一个月。

逻辑:

  1. 2011 年 1 月,A 医生有 2 名新患者
  2. 2011 年 2 月,A 医生有 1 名新患者
  3. 2011 年 1 月,B 医生有 3 名新患者
  4. 2011 年 2 月,B 医生有 1 名新患者

这是我想要的结果:

+--------+-------+------+----------------+
| doctor | month | year | # new patients |
+--------+-------+------+----------------+
| A      |     1 | 2011 |              2 |
| A      |     2 | 2011 |              1 |
| B      |     1 | 2011 |              3 |
| B      |     2 | 2011 |              1 |
+--------+-------+------+----------------+

你能帮我开始吗?

4

3 回答 3

2

更正了乔的答案的语法

select doctor, year, month, count(patient) [num_new]
from (select doctor, patient, min(MONTH([datefield])) [month], min(YEAR([datefield]))  [year]
    from [dbo].[test_aakruti]
    group by doctor, patient) as table1
group by doctor, [year], [month]
于 2012-09-13T23:07:21.480 回答
2

只需将其分解为几个步骤:

  • 确定给定患者和医生的第一个月是哪一个月(即select doctor, patient, min(month) from mytable group by doctor, patient

  • 通过按医生和月份对先前结果进行分组来计算新患者的数量

应该能够使用子查询或临时表/表变量来执行此操作,无论您喜欢哪种方式。

编辑:我写的查询可能看起来像:

select doctor, year, month, count(1) [num_new]
from
(
    select doctor
           ,patient
           ,datepart(mm, min(datefield)) [month]
           ,datepart(yyyy, min(datefield)) [year]
    from mytable
    group by doctor, patient
) sub
group by doctor, year, month
于 2012-09-13T22:40:34.977 回答
1

获取一个月的患者总数非常简单:

SELECT Doctor, YEAR(datef) AS yr, MONTH(datef) AS mnth, COUNT(patient) AS totPatients FROM ##doctors
GROUP BY Doctor, YEAR(datef), MONTH(datef)

Doctor  yr      mnth    totPatients
A       2011    1       3
A       2011    2       2
B       2011    1       3
B       2011    2       2

但是获取新患者的数量稍微复杂一些。为此,我们需要获得每个患者的第一次访问。这可以通过以下方式完成:

SELECT doctor, patient, MIN(MONTH(datef)) AS Mnth, MIN(YEAR(datef)) AS Yr FROM ##doctors GROUP BY doctor, patient

然后,通过将两者结合起来,我们得到了想要的结果:

WITH fstVisit AS (
    SELECT doctor, patient, min(month(datef)) AS Mnth, min(year(datef)) AS Yr FROM ##doctors GROUP BY doctor, patient
    )
    SELECT Doctor,  yr, mnth, COUNT(patient) AS totPatients FROM fstVisit
    GROUP BY Doctor, yr, mnth

Doctor  yr      mnth    totPatients
A       2011    1       2
A       2011    2       1
B       2011    1       3
B       2011    2       1
于 2012-09-13T22:47:57.033 回答