每月获取新数据

时间:2012-09-13 22:21:16

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

我的数据如下:

+--------+-----------+---------+
| 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. 医生A 2011年1月有2名新患者
  2.   
  3. 医生A 2011年1月新病人
  4.   
  5. 医生B 2011年1月有3名新患者
  6.   
  7. 医生B为2011年2月新病人
  8.   

这是我想要的结果:

+--------+-------+------+----------------+
| doctor | month | year | # new patients |
+--------+-------+------+----------------+
| A      |     1 | 2011 |              2 |
| A      |     2 | 2011 |              1 |
| B      |     1 | 2011 |              3 |
| B      |     2 | 2011 |              1 |
+--------+-------+------+----------------+
你可以帮我开始吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

修正了Joe的回答语法

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]

答案 2 :(得分: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