2017-10-19 146 views
1

我想统计未来约会在同一天进行激活约会位置。我预计给定日期范围的每个Patient_ID有多个计数。我不确定是否需要临时表或子查询是否可用。SQL子选择返回多个值

从下面这个代码是我的错误:

子查询返回多个值。当 子查询遵循=,!=,<,< =,>,> =或当子查询用作 表达式时,这是不允许的。

定义:

  • Appointment_DateTime - (日期)是实际约会事件
  • DateTime_Scheduled - (日期)是未来的约会
  • 说明的记录标记 - (文字)是位置描述
  • Patient_ID - (int)是唯一的患者ID
  • Appointment_ID - (int)是唯一的约会ID

SQL

SELECT 
    loc.Description 
,Count(app.Appointment_ID) 

FROM [Ntier_HARH].[PM].[Appointments] app 

join [Ntier_HARH].[PM].[Resources] res 
    on res.Resource_ID = app.Resource_ID 
join [Ntier_HARH].[PM].[Practitioners] doc 
    on doc.Practitioner_ID = res.Practitioner_ID 
join [Ntier_HARH].[PM].[Scheduling_Locations] loc 
    on loc.Scheduling_Location_ID = app.Scheduling_Location_ID 

where  
    cast(app.DateTime_Scheduled as date) = '2017-01-16' 
    and app.status <> 'X' 
    and cast(app.Appointment_DateTime as date) = 
     (Select cast(DateTime_Scheduled as date) 
     from [Ntier_HARH].[PM].[Appointments] 
     where Patient_ID = app.Patient_ID) 

group by loc.Description 
+0

望着查询,我相信你需要在子查询'min'或'max'聚集,或者你可以用'Row_Number'避免子查询 –

+0

不要你还需要组由PatientId ? –

回答

1

您可以使用的in代替=

where 

cast(app.DateTime_Scheduled as date) = '2017-01-16' 
and app.status <> 'X' 
and cast(app.Appointment_DateTime as date) IN (Select cast(DateTime_Scheduled as date) from [Ntier_HARH].[PM].[Appointments] where Patient_ID = app.Patient_ID) 

group by loc.Description 
+0

就是这样!男孩很简单。 –

0

你不也是由PatientId需要组?如果您只想按位置进行约会计数,则子查询不是必需的。我不明白为什么其他两张桌子也是必需的。

SELECT l.Description, Count(a.Appointment_ID) 

FROM [Ntier_HARH].[PM].[Appointments] a 
    join [Ntier_HARH].[PM].[Scheduling_Locations] l 
     on l.Scheduling_Location_ID = a.Scheduling_Location_ID 

where cast(a.DateTime_Scheduled as date) = '2017-01-16' 
    and a.status <> 'X' 

group by l.Description 
+0

如果日期与每个patient_ID匹配且没有匹配的日期,我只想对Appintment_ID进行计数。 –