在T-SQL中按类别更新
我有一张这样的桌子:在T-SQL中按类别更新,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张这样的桌子: id | ImportDate | ExpirationDate 1 | 2014-08-21 | 2014-08-21 1 | 2014-08-19 | 2014-08-20 2 | 2014-08-20 | 2014-08-20 2 | 2014-08-19 | 2014-08-19 现在我只想更新那些具有maximportDate并将主题ExpirationDate设置为9999-12-31的行。所以第1行和第3行。代码是: update table
id | ImportDate | ExpirationDate
1 | 2014-08-21 | 2014-08-21
1 | 2014-08-19 | 2014-08-20
2 | 2014-08-20 | 2014-08-20
2 | 2014-08-19 | 2014-08-19
现在我只想更新那些具有maximportDate并将主题ExpirationDate设置为9999-12-31的行。所以第1行和第3行。代码是:
update table
set ExpirationDate = '9999-12-31'
Where
ImportDate = (SELECT MAX(ImportDate) FROM table
group by id
)
但我得到了一个错误,子查询返回了超过1个值。当子查询在=、!=、=或者当子查询用作表达式时。”
我似乎有点奇怪,因为子查询中的SELECT假设每个id只返回一个日期。您知道如何实现此更新吗?错误似乎是不言自明的。要解决此问题,可以使用相关子查询:
update t
set ExpirationDate = '9999-12-31'
from table t
Where ImportDate = (SELECT MAX(ImportDate)
FROM table t2
WHERE t2.id = t.id
)
这个错误似乎不言自明。要解决此问题,可以使用相关子查询:
update t
set ExpirationDate = '9999-12-31'
from table t
Where ImportDate = (SELECT MAX(ImportDate)
FROM table t2
WHERE t2.id = t.id
)
我更喜欢的另一种风格,因为它对我来说更具可读性
with cte as (
select *
, row_number() over (
partition by [id]
order by [ImportDate] desc
) as [r]
from dbo.Table
)
update cte
set ImportDate = '9999-12-31'
where [r] = 1
我更喜欢的另一种风格,因为它对我来说更具可读性
with cte as (
select *
, row_number() over (
partition by [id]
order by [ImportDate] desc
) as [r]
from dbo.Table
)
update cte
set ImportDate = '9999-12-31'
where [r] = 1
我无法将alias与update station一起放置。但是:更新表集合ExpirationDate='9999-12-31',其中ImportDate=从表t2中选择MAXImportDate,其中t2.id=id;生成相同的错误。我发现在t-sql中,使用别名进行更新有点棘手。工作的代码应该是这样的:从表t1中更新t1 set t1.ExpirationDate='9999-12-31',其中t1.ImportDate=从表t2中选择MAXImportDate,其中t2.id=t1.id@阿瑟81。您可以使用别名。它必须在from子句中定义。我不能用update STATTENT放置别名。但是:更新表集合ExpirationDate='9999-12-31',其中ImportDate=从表t2中选择MAXImportDate,其中t2.id=id;生成相同的错误。我发现在t-sql中,使用别名进行更新有点棘手。工作的代码应该是这样的:从表t1中更新t1 set t1.ExpirationDate='9999-12-31',其中t1.ImportDate=从表t2中选择MAXImportDate,其中t2.id=t1.id@阿瑟81。您可以使用别名。它必须在from子句中定义。