我有一张病人,他们的服务,服务日期等表...如果病人在一个月内有6项以上的独特服务,那么在我的选择陈述中 我想要一个新专栏来说明#34; Full Month"在它。
答案 0 :(得分:0)
你需要一个简单的小组
设置数据
create table #patient
(
patientId int,
serviceId int,
dt date
)
insert into #patient values
(1, 1, '2016-01-02'),
(1, 1, '2016-01-05'),
(1, 1, '2016-01-07'),
(1, 1, '2016-01-12'),
(1, 1, '2016-01-16'),
(1, 1, '2016-01-20'),
(1, 1, '2016-01-25'),
(1, 2, '2016-01-02'),
(1, 2, '2016-01-02'),
(2, 1, '2016-01-02'),
(2, 1, '2016-01-02')
获取结果
select patientId, serviceId, count(*) AS Cnt
, case
when count(*) >= 6 then 'Full Month'
else 'Not Full Month'
end AS YourNewColumn
from #patient
group by patientId, serviceId, month(dt)
会显示
+-----------+-----------+-----+----------------+
| patientId | serviceId | Cnt | YourNewColumn |
+-----------+-----------+-----+----------------+
| 1 | 1 | 7 | Full Month |
| 1 | 2 | 2 | Not Full Month |
| 2 | 1 | 2 | Not Full Month |
+-----------+-----------+-----+----------------+
答案 1 :(得分:-1)
我想您可以对您的特定患者标识符使用GROUP BY
查询,以获取特定患者在一个日期范围内的所有结果,如下所示:
SELECT PatientId,
CASE WHEN COUNT(ServiceId) > 5 THEN 1 ELSE 0 END AS FullMonth
FROM Patients
WHERE ServiceDate BETWEEN @Start AND @End
GROUP BY PatientId, ServiceId