简体   繁体   English

根据列值返回SQL Server列名和相应的值

[英]Return SQL Server column name and corresponding value based on column value

How do I return column name and value based on column value for each record ? 如何根据每条记录的列值返回列名和值?

I have this: 我有这个: 我有这个

I would like to update 我想更新

first_color with color name having highest value first_color,颜色名称具有最高值

first_value with highest value and so on, as shown in the below snippet. first_value具有最高值,依此类推,如下面的代码段所示。

Note: This is just an example, I have over 100 columns for which I need column name & value for top 5 columns/values. 注意:这只是一个示例,我有超过100列我需要列名称和前5列/值的值。 So, looking for a dynamic sql if possible. 所以,如果可能的话,寻找动态的SQL。

我要这个

I got till this point, using cross apply. 我到目前为止,使用交叉申请。

在此输入图像描述

SQL Server Approach SQL Server方法

Perhaps with a CROSS APPLY in concert with a ROW_NUMBER() 也许与CROW APPLY一起使用ROW_NUMBER()

Example

Select A.* 
      ,B.*
 from  YourTable2 A
 Cross Apply (Select First_Color  = max(case when RN=1 then Item end)  
                    ,First_Value  = max(case when RN=1 then Value end)  
                    ,Second_Color = max(case when RN=2 then Item end)  
                    ,Second_Value = max(case when RN=2 then Value end)  
                From (Select *,RN=Row_Number() over (Order by Value Desc)
                        From ( values ('Red',Red)
                                     ,('Green',Green)
                                     ,('Blue',Blue)
                                     ,('Black',Black)
                               ) B1 (Item,Value)
                     ) B2
             ) B

Returns 返回

unique_id   Red Green   Blue    Black   First_Color First_Value Second_Color    Second_Value
abc12       1   2       4       7       Black       7           Blue            4
mnc23       2   4       1       3       Green       4           Black           3

With new information, this will unpivot your data without having to to go dynamic. 有了新的信息,这将无需动态地取消数据。 You can then PIVOT if desired 如果需要,你可以PIVOT

Select A.unique_id
      ,C.*
      ,ColNr = Row_Number() over (Partition By unique_id Order by Value Desc)
 From YourTable A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
                Select Field = a.value('local-name(.)','varchar(100)')
                      ,Value = a.value('.','varchar(max)')  
                 From  B.XMLData.nodes('/row')  as C1(n)
                 Cross Apply C1.n.nodes('./@*') as C2(a)
                 Where a.value('local-name(.)','varchar(100)') not in ('unique_id')
             ) C

Returns 返回

unique_id   Field   Value   ColNr
abc12       Black   7       1
abc12       Blue    4       2
abc12       Green   2       3
abc12       Red     1       4
mnc23       Green   4       1
mnc23       Black   3       2
mnc23       Red     2       3
mnc23       Blue    1       4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM