【问题标题】:Select into with max()用 max() 选择
【发布时间】:2013-09-11 03:07:21
【问题描述】:

我有一个基本查询,用于确定表中列的最大值:

select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id

这会产生大约 580 行(整个表有超过 2400 行)。

这对我的查询结果很好,但我不知道如何根据最大值将 580 行插入到新的行中。我意识到这不是正确的代码,但我的想法看起来像这样:

select * into new_table from rev_code_lookup where max(revenue_code_version)

【问题讨论】:

  • SELECT INTO using Oracle的可能重复
  • 这个不是Oracle的,下次一定要指定SQL server,以免混淆。谢谢

标签: sql sql-server insert max


【解决方案1】:

您可以使用row_number() 函数来获取您想要的数据。结合其他答案将结果插入表中(我已经组成了几个额外的列作为示例):

Select
  x.revenue_code_id,
  x.revenue_code_version,
  x.update_timestamp,
  x.updated_by
From (
  Select
    revenue_code_id,
    revenue_code_version,
    update_timestamp,
    updated_by,
    row_number() over (partition by revenue_code_id Order By revenue_code_version Desc) as rn
  From
    revenue_code_lookup
) x
Where
  x.rn = 1

Example Fiddle

【讨论】:

  • 谢谢,这得到了我需要的东西。里面有一些我以前没有见过/使用过的东西,所以我要去了解它们。
【解决方案2】:

无论选择的复杂性如何,在另一个表中的插入始终是相同的方式:

insert into table
[unbeliavablycomplicatedselecthere]

所以在你的情况下:

insert into new_table
select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id

同样,如果您需要创建一个全新的表,请先执行此操作:

CREATE TABLE new_table
AS
select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id

这将创建相应的表架构,然后您可以执行前面的查询来插入数据。

【讨论】:

  • 好的,如果我有另外两个字段要添加到我的插入语句中怎么办?我在源表中有 4 个字段,一个是文本,另一个是日期。但我需要根据收入代码版本最大值插入。
  • 正如我所说,无论您的查询有多复杂,模式都是一样的。因此,只需更改您的查询并将其添加到 create table asinsert into 的末尾。
  • 当我执行以下操作时,我将所有行从源插入到目标中,而不仅仅是最大值。我显然有问题...'select A.revenue_code_id, max(revenue_code_version) ASincome_code_version, description, last_updated INTO rev_code2 from rev_code_lookup A group by A.revenue_code_id, description, last_updated order by max(revenue_code_version) desc'
  • 抱歉,我刚刚意识到您的问题不在于 INSERT INTO 的语法,而在于 max.在这种情况下,请参阅@Laurence 的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多