子查询在case语句中返回了超过1行

时间:2017-01-25 02:59:51

标签: sql

我一直在处理一个查询,在子查询中,我在某些条件下选择了列Cust_Status

select distinct 
    C.Cust_Code [Cust #],
    C.Cust_Start_Date [Start Date],
    C.Cust_End_date [End Date],
    (select 
         Cust_Status = (case  
                           when cast(CUST_UPDATE_DATE_LT as DATE) = cast('2017-01-23 00:00:00' as Date)
                              then 'V' 
                           when cast(CUST_UPDATE_DATE_LT as DATE) = cast('2017-01-22 00:00:00' as Date) 
                              then 'I'  
                        end)  
     from tblCustomers) [Cust Status],
    M.Machine_ID,
    M.Machine_Location
from 
    tblCustomers C   
inner join 
    tblMachine M on C.Cust_Mach_Pkey = M.Pkey

当我运行此查询时,我收到错误

  

子查询返回的值超过1个值。

当我删除案例中的子查询时,它没问题。但我相信这两个日期条件只有1条记录。所以不确定我的子查询如何返回超过1个值。请赐教。

1 个答案:

答案 0 :(得分:0)

我猜你只想比较最新的日期。如果是这样,有更简单的方法:

select C.Cust_Code as [Cust #], C.Cust_Start_Date as [Start Date],
       C.Cust_End_date as [End Date],
       (case when max(cast(CUST_UPDATE_DATE_LT as DATE)) = '2017-01-23'
             then 'V'
             when max(cast(CUST_UPDATE_DATE_LT as DATE)) = '2017-01-22'
             then 'I'
        end) as Cust_status 
      M.Machine_ID,
      M.Machine_Location
from tblCustomers C inner join
     tblMachine M
     on C.Cust_Mach_Pkey = M.Pkey
group by C.Cust_Code, C.Cust_Start_Date, C.Cust_End_date,
         M.Machine_ID, M.Machine_Location