SQL子选择返回多个值

时间:2017-10-19 13:56:13

标签: sql sql-server tsql subquery

我想计算位置在活动约会的同一天制作的未来约会。我希望在给定日期范围的情况下,每个 Patient_ID 有多个计数。我不确定我是否需要临时表或者子查询是否有效。

从下面的代码中我得到错误:

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

说明:

  • Appointment_DateTime - (Date)是实际预约事件
  • 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

2 个答案:

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

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