首页 > 解决方案 > 尝试用不同的值更新所有行

问题描述

当我为一排做这件事时,它起作用了

update test set counte = 
(select  cOUNT(*)as counte from en_cours ,
test where DATEDIFF(DAY, en_cours.date, test.date)=0 
and  test.date='2019-11-13' group by test.date)
where test.date='2019-11-13'

但是当我对所有行都这样做时

update test set counte =
(select  COUNT(*) from en_cours ,
test where DATEDIFF(DAY, en_cours.date, test.date)=0  
group by test.date) 
where test.date= (select  CONVERT(date , en_cours.date) from en_cours)

他们说

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

请有任何帮助

标签: sqlsql-server

解决方案


您的错误消息是不言自明的。您不能设置像 WHERE 10 = (A list of Integer like - 10,20,30) 这样的条件。当您使用 =, !=, <, <= , >, >= 符号时,子查询必须返回一个值,因为您的查询返回的值超过 1 个并且错误就在那里。您可以使用以下 CTE 来满足您的要求-

WITH CTE AS(
    select  test.date,COUNT(*) T
    from en_cours 
    INNER JOIN test 
        ON en_cours.date = test.date
    group by test.date
)

update A
SET A.counte = B.T
FROM Test A
INNER JOIN CTE B ON A.Date = B.Date

推荐阅读