[英]SQL update using same table subquery results
我有一個這樣的數據表:
-------------+-------------+-------
| foo_date | description | flag |
-------------+-------------+-------
| 2014-01-01 | asdf 123 | 1 |
-------------+-------------+-------
| 2014-01-01 | FOO | 1 |
-------------+-------------+-------
| 2014-01-02 | asdf 456 | 1 |
-------------+-------------+-------
我正在嘗試將描述不為“ FOO”的任何行的標志設置為0,並且在同一日期存在一行為“ FOO”的行。 因此,在此示例數據集中,第一行將獲得flag = 0,因為同一日期有一個FOO,但第三行則不會,因為在該日期沒有匹配的FOO。 這是我想出的方法,但它並不是最有效的方法。
UPDATE
foo_table t1
JOIN
(
SELECT
*
FROM
foo_table
WHERE
(foo_date) IN
(
SELECT
foo_date
FROM
foo_table
WHERE
description LIKE 'FOO%'
)
AND description NOT LIKE 'FOO%'
) AS t2
ON
(
t1.foo_date = t2.foo_date
AND t1.description = t2.description
)
SET
t1.flag = 0
update t1
set t1.flag = 0
from foo_table t1
where t1.description <> 'FOO'
and exists (select *
from foo_table t2
where t2.foo_date=t1.foo_date
and t2.description = 'FOO')
根據您的數據,這可能會更有效:
update t1
set t1.flag = 0
from foo_table t1
where isnull(t1.description,'') <> 'FOO'
and t1.foo_date in (select t2.foo_date
from foo_table t2
where t2.description = 'FOO')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.