从最大查询中选择列名称

Hug*_*ron 6 sql t-sql sql-server sql-server-2008

我有一个类似这样的查询:

 ;WITH t as
(
select 1 as RowNumber, 1 as ObjectID, 10 as [Col1],  20 as [Col2],  20 as [Col3],  20 as [Col4] UNION ALL
select 2 as RowNumber, 2 as ObjectID, 20 as [Col1],  30 as [Col2],  40 as [Col3],  50 as [Col4]
)
SELECT  RowNumber, ObjectID,
        (
        SELECT  MAX(Amount)
        FROM    (
                SELECT  [Col1] AS Amount
                UNION ALL
                SELECT  [Col2]
                UNION ALL
                SELECT  [Col3]
                UNION ALL
                SELECT  [Col4]
                ) d
       WHERE   Amount > 0
        )
FROM    t
Run Code Online (Sandbox Code Playgroud)

查询工作正常,但我想知道Max(金额)来自哪里.

所以在我的结果集中,除了(RowNumber,ObjectId,Amount)之外,我希望列的名称(Col1,Col2,Col3,Col4)为String.

有没有办法做到这一点?

来自评论的编辑问题:如果两列具有相同的最大值,它可以是一列?是的,它可以是一个.任何列名都可以,只要我知道它可能来自哪里.

使用SQL Server 2008

gbn*_*gbn 5

不要MAX:使用TOP避免聚合/ GROUP BY.

它还可以使用WITH TIES处理重复项

我不确定你所拥有的是伪代码还是子查询,但这应该做你想要的

 SELECT TOP 1 -- WITH TIES if needed
     *
 FROM
     (
     SELECT  RowNumber, ObjectID, [Col1] AS Amount, 'Col1' AS ColName
     FROM table
     UNION ALL
     SELECT  RowNumber, ObjectID, [Col2], 'Col2' AS ColName
     FROM table
     UNION ALL
     SELECT  RowNumber, ObjectID, [Col3], 'Col3' AS ColName
     FROM table
     UNION ALL
     SELECT  RowNumber, ObjectID, [Col4], 'Col4' AS ColName
     FROM table
     ) foo
 WHERE   Amount > 0
 ORDER BY Amount DESC
Run Code Online (Sandbox Code Playgroud)

您的主要问题是,无论您如何操作,都必须触摸表4次,因为子查询只返回一个值.我也看不到ROW_NUMBER解决方案(但可能有一个...... :-)


8kb*_*8kb 1

您可以结合使用UNPIVOTOUTER APPLY

;WITH t as     (
select 1 as RowNumber, 1 as ObjectID, 10 as [Col1],  20 as [Col2],  
       20 as [Col3],  20 as [Col4] UNION ALL
select 2 as RowNumber, 2 as ObjectID, 20 as [Col1],  30 as [Col2],  
       40 as [Col3],  50 as [Col4] )
SELECT 
  RowNumber,
  ObjectID,
  ColName,
  ColAmount
FROM t
OUTER APPLY (
  SELECT TOP 1 
    ColName,
    ColAmount
  FROM 
    (
      SELECT
        Col1,
        Col2,
        Col3,
        Col4
    ) x 
    UNPIVOT (
      ColAmount FOR ColName IN (Col1, Col2, Col3, Col4) 
    ) y
   WHERE ColAmount > 0
   ORDER BY ColAmount DESC
 ) z
Run Code Online (Sandbox Code Playgroud)

结果:

RowNumber   ObjectID    ColName   ColAmount
----------- ----------- --------- -----------
1           1           Col2      20
2           2           Col4      50
Run Code Online (Sandbox Code Playgroud)