在WHERE子句中使用聚合进行SQL更新

时间:2012-08-31 19:30:32

标签: sql sql-server-2005

我试图设置列日期的日期字段,让我们说“10月11日”'在表1中,当表2的所有金额的总和与该id相关(通过fk_id)= 0.这就是我的意思:

FROM:

表1

    id    date
    1     10/11/2011
    2      
    3     10/12/2011

表2

    fk_id    amount
    1     200
    2     0
    2     0
    3     100

TO:

表1

    id    date
    1     10/11/2011
    2     10/11/2012
    3     10/12/2011

表2

    fk_id    amount
    1     200
    2     0
    2     0
    3     100

这就是我目前的情况:

update table1
set date = '10/11/2012
FROM table1 inner join table 2 on table1.id = table2.fk_id
HAVING sum(table2.amount) = 0

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:5)

UPDATE table1 
SET date = '10/11/2012' 
FROM table1 
WHERE id IN (SELECT FK_ID FROM table2 GROUP BY FK_ID HAVING SUM(Amount)=0)

答案 1 :(得分:0)

这应该有效:

UPDATE T1
SET [date] = '20121011'
FROM table1 T1
INNER JOIN (SELECT fk_id, SUM(amount) Amount
            FROM table2
            GROUP BY fk_id
            HAVING SUM(amount) = 0) T2
ON T1.id = T2.fk_id