SQL更新列以使用另一个表中的最大数字,但每个组增加1

时间:2018-03-06 15:41:30

标签: sql sql-server

假设我有一个表(VersionTEMP),其中包含以下3个条目:

--------------------------------
| VersionName    | VersionID   |
--------------------------------
| a-seattle      |             |
| e-everett      |             |
| k-kitsap       |             |
--------------------------------

我需要从另一个表(VersionHistory)中提取最大VersionID,然后将该数字+ 1分配给VersionTEMP中的每个唯一VersionName。因此,如果VersionHistory的最大VersionID为715,我的结果将是:

--------------------------------
| VersionName    | VersionID   |
--------------------------------
| a-seattle      |     716     |
| e-everett      |     717     |
| k-kitsap       |     718     |
--------------------------------

我将如何做到这一点?

3 个答案:

答案 0 :(得分:0)

SQL Server,快速而肮脏:

select appname, versionno + 1 from versionhistory where appname = 'Seattle'
UNION ALL
select appname, versionno + 1 from versionhistory where appname = 'Everett'
UNION ALL
select appname, versionno + 1 from versionhistory where appname = 'Kitsap'
GO

或者,获取所有应用

select appname, versionno + 1 from versionhistory order by whatever

可与CTE一起使用如下:

with CTE as (
    select appname as App, versionno + 1 as VersionNum from versionhistory where appname = 'Seattle'
    UNION ALL
    select appname as App, versionno + 1 as VersionNum from versionhistory where appname = 'Everett'
    UNION ALL
    select appname as App, versionno + 1 as VersionNum from versionhistory where appname = 'Kitsap'
    )
    insert into versionTEMP(appname, versionno) select App, VersionNum from CTE

OR

with CTE as (
select appname App, versionno + 1 VersionNum from versionhistory order by whatever
        )
        insert into versionTEMP(appname, versionno) select App, VersionNum from CTE

CTE不是必需的:

insert into versionTemp (appname, versionid) select h.appname, h.versionid + 1 from versionhistory h

update versionTemp set appname = h.appname, versionid = h.versionid + 1 from versionhistory h

答案 1 :(得分:0)

在SQL中,您可以使用可更新的CTE:

with toupdate as (
      select t.*, row_number() over (order by (select null)) as seqnum
      from t
     )
update toupdate
    set versionId = 714 + seqnum;

如果您想动态提取数字:

with toupdate as (
      select t.*, row_number() over (order by (select null)) as seqnum
      from t
     )
update toupdate
    set versionId = ot.maxversionid + seqnum
    from toupdate cross join
         (select max(versionid) as maxversionid from othertable) ot;

答案 2 :(得分:0)

感谢Gordon的快速回复。你的动态答案解决了我的问题。 我确实改变了一些变量并在底部添加了一个where语句,所以看起来像这样:

with [Update] as (
      select [VersionName], row_number() over (order by [VersionName]) as [SeqNum]
      from VersionTEMP Group By [VersionName]
     )
update [VersionTEMP]
    set [VersionID] = [MaxHistoryVersionID].[MaxVersionID] + [SeqNum]
    from [Update] cross join
         (select max(VersionID) as [MaxVersionID] from [OrderHistory]) as [MaxHistoryVersionID]
    where [VersionTemp].[VersionName] = [Update].[VersionName]

再次感谢!