查询和子查询遇到问题:SQL子查询返回了多个值

时间:2018-10-08 20:13:53

标签: sql-server

这是我要运行的内容,但出现错误。有什么想法吗?

SELECT 
   Client_Account_Name, 
   (
       select Distinct t1.Contact_email as temp3 
       from Order_Log_SFDC t1
       inner join
       (
          select max(Event_Date_Time) Event_Date_Time, Client_Account_Name
          from Order_Log_SFDC
          group by Client_Account_Name
       )  t2 on t1.Client_Account_Name = t2.Client_Account_Name
              and t1.Event_Date_Time = t2.Event_Date_Time
   ) as Email,

    MIN(Source) as source, 
    SUM(Final_Quote) as Total, 
    MIN(Event_Date_Time) AS min_date, 
    Max(Event_Date_Time) as max_date, 
    count(Distinct Event_Date_Time) as numOrders

FROM Order_Log_SFDC
Group By Client_Account_Name

这是错误:

  

SQL错误[512] [21000]:子查询返回了多个值。
  当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
   SQL错误[512] [21000] :子查询返回了多个值。
  当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
   SQL错误[512] [21000] :子查询返回了多个值。
  当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
    SQL错误[512] [21000] :子查询返回了多个值。
  当子查询遵循=,!=,<,<=,>,> =时,不允许这样做   或将子查询用作表达式时。
  子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
            没有声明光标。

2 个答案:

答案 0 :(得分:3)

像这样尝试...

SELECT
    Client_Account_Name,
    Email = CONVERT(VARCHAR(200), SUBSTRING(MAX(CONVERT(BINARY(8), Event_Date_Time) + CONVERT(VARBINARY(200), Contact_email)), 9, 200)),
    source  = MIN(Source),
    Total = SUM(Final_Quote),
    min_date = MIN(Event_Date_Time),
    max_date = MAX(Event_Date_Time),
    numOrders = COUNT(DISTINCT Event_Date_Time)
FROM
    Order_Log_SFDC
GROUP BY
    Client_Account_Name;

答案 1 :(得分:0)

SELECT 
   Client_Account_Name, 
   (
       SELECT TOP 1 Contact_email 
       FROM Order_Log_SFDC t2
       WHERE t2.Client_Account_Name = t1.Client_Account_Name
       ORDER BY Event_Date_Time DESC
   ) As Email,
   MIN(Source) as source, 
   SUM(Final_Quote) as Total, 
   MIN(Event_Date_Time) AS min_date, 
   Max(Event_Date_Time) as max_date, 
   count(Distinct Event_Date_Time) as numOrders

FROM Order_Log_SFDC t1
Group By Client_Account_Name