【问题标题】:return column name of the maximum value in sql server 2012返回sql server 2012中最大值的列名
【发布时间】:2015-02-14 06:22:11
【问题描述】:

我的桌子看起来像这样(完全不同的名字)

ID   Column1--Column2---Column3--------------Column30 
X       0       2          6       0101          31

我想找到 Column1 到 Column30 的 第二个最大值 值,并将 column_Name 放在单独的列中。

第一行看起来像:

ID   Column1--Column2---Column3--------------Column30------SecondMax
X       0       2          6       0101          31         Column3

查询:

      Update Table
      Set SecondMax= (select Column_Name from table  where ...) 

【问题讨论】:

  • 这张表是不是只有一条记录?
  • @BenisonSam 不,亲爱的,它有 50 万条记录
  • 你是怎么处理领带的?

标签: sql stored-procedures sql-server-2012 dynamic-sql


【解决方案1】:
with unpvt as (
    select id, c, m
    from T
    unpivot (c for m in (c1, c2, c3, ..., c30)) as u /* <-- your list of columns */
)
update T
set SecondMax = (
    select top 1 m
    from unpvt as u1 
    where
        u1.id = T.id
        and u1.c < (
            select max(c) from unpvt as u2 where u2.id = u1.id
        )                    
    order by c desc, m
)

我真的不喜欢依赖 top 但这不是一个标准的 sql 问题。除了按字母排序返回第一列名称之外,它对平局没有任何作用。

您可以通过以下条件使用修改来获得“第三个最大值”。 (很明显,常数 2 来自 3 - 1。)您的 SQL Server 版本也允许您在那里使用变量。我认为 SQL 2012 也支持 limit 语法,如果它比 top 更可取的话。由于它也适用于前 0 名和前 1 名,因此您也许可以在循环中运行此查询以填充从第 1 到第 30 的所有“最大值”。

一旦你开始有联系,你最终会得到一个“第三十个最大值”,它是空的。不过,请确保涵盖这些情况。

        and u1.c < all (
            select top 2 distinct c from unpvt as u2 where u2.id = u1.id
        )

在我考虑之后。如果您要对这么多列进行排名和更新,那么使用适当的排名函数并一次完成所有更新可能会更有意义。即使字母排序仍然是任意的,您也可以更好地处理平局。

with unpvt as (
    select id, c, m, row_number() over (partition by id order by c desc, m) as nthmax
    from T
    unpivot (c for m in (c1, c2, c3, ..., c30)) as u /* <-- your list of columns */
)
update T set
    FirstMax = (select c from unpvt as u where u.id = T.id and nth_max = 1),
    SecondMax = (select c from unpvt as u where u.id = T.id and nth_max = 2),
    ...
    NthMax = (select c from unpvt as u where u.id = T.id and nth_max = N)

【讨论】:

  • 反透视操作生成的列的名称。尝试自己运行 unpvt 查询,看看它是如何工作的。
  • 是的,我做到了。虽然我会咬紧牙关不问你为什么要这个。
  • :D 这是一个完全不同的问题。列名是城市,它们的值是每个客户访问的数量。我已经找到了每个客户最喜欢的城市。现在,我想找到第二个最喜欢的。
  • 我希望它对你有用。但是您可能会发现自己做了很多反透视,然后问自己为什么不首先以这种方式存储数据。
  • 领带不是问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
  • 2017-02-07
相关资源
最近更新 更多