子查询返回多个值...不允许这样做

时间:2016-08-02 22:19:30

标签: sql sql-server

declare @week1S DATE = '07/01/2016';
declare @week1E DATE = '07/07/2016';

WITH A as (
SELECT COUNT(ARB_accomplished) as ARB_accomplished_CNT 
FROM arbimport
WHERE Requested_date between @week1S and @week1E AND arb_accomplished LIKE 'Y'
GROUP BY dispatch_group_name
)
Update ArbitrageResponse
Set arb_count1 = (SELECT ARB_accomplished_CNT FROM A)

我正在尝试根据另一个表中的响应计数更新一个表中的列。我正在尝试对dispgroup进行分组,因为我的导入表很大,我试图将其过滤到选定的日期范围。我将不得不运行这么多,所以保持变量但不是必要的很酷。

我希望我的响应表每周都会记录响应,因此我只需要将列添加到此表中,这就是我进行更新的原因。

我收到错误

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

我不确定这是否与我的变量有关,因为它们在我的子查询中被调用 - 我知道我的子查询返回了许多不同行的聚合结果。有一个更好的方法吗?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

set  @countaccomplished = SELECT COUNT(ARB_accomplished) as ARB_accomplished_CNT 
FROM arbimport
WHERE Requested_date between @week1S and @week1E AND arb_accomplished LIKE 'Y'
GROUP BY dispatch_group_name WHERE DISPATCH_GROUP_NAME = SOMETHING

Update ArbitrageResponse
Set arb_count1 = @countaccomplished 

OR

WITH A as (
SELECT COUNT(ARB_accomplished) as ARB_accomplished_CNT, dispatch_group_name 
FROM arbimport
WHERE Requested_date between @week1S and @week1E AND arb_accomplished LIKE 'Y'
GROUP BY dispatch_group_name
)
Update b 
Set b.arb_count1 = a.ARB_accomplished_CNT  
FROM ArbitrageResponse b where a.dispatch_group_name= b.dispatch_group_name

答案 1 :(得分:0)

在不知道桌子结构的情况下,这只是猜测:

WITH A as (
      SELECT dispatch_group_name, COUNT(ARB_accomplished) as ARB_accomplished_CNT 
      FROM arbimport
      WHERE Requested_date between @week1S and @week1E AND arb_accomplished LIKE 'Y'
      GROUP BY dispatch_group_name
     )
UPDATE ar
    SET arb_count1 = a.ARB_accomplished_CNT
    FROM ArbitrageResponse ar JOIN
         A
         ON ar.dispatch_group_name = a.dispatch_group_name