简体   繁体   English

根据列值动态获取列名称

[英]Get column name based on column value dynamically

I have a table with "User Name", "Brand" and "Value" as columns. 我有一个表“User Name”,“Brand”和“Value”作为列。 Each Manager and their associates are responsible for max 3 brand and these brands can change from manager to manager. 每位经理及其员工都负责max 3品牌,这些品牌可以从经理变为经理。 Right now User name, Brand and their value are in row format like below. 现在用户名,品牌及其价值的行格式如下。

           User Name    Brand Name  Value
             User 1             Puma    10
             User 1            Adidas   20
             User 1             Nike    30
             User 2             Puma    40
             User 2           Adidas    50
             User 2             Nike    60
             User 3             Puma    70
             User 3           Adidas    80
             User 3             Nike    90  

Using a "case-when" I achieved below, but the problem is, these brand can change based on the manager. 使用“case-when”我在下面实现,但问题是,这些品牌可以根据经理进行更改。 Example. 例。 Manager -1 can be responsible for Puma, Nike, Adidas but Manager -2 can be responsible for X, Y, Z Brands. 经理-1可以负责彪马,耐克,阿迪达斯,但经理-2可以负责X,Y,Z品牌。

            User Name   Brand -1    Brand -2  Brand -3
             User 1       10      20        30
             User 2       40      50        60
             User 3       70      80        90

My desired state is to get the Brand name in column format like below. 我希望的状态是以下面的列格式获取品牌名称。

For Manager - 1 经理 - 1

            User Name   PUMA      ADIDAS      NIKE
             User 1          10    20              30
             User 2          40    50              60
             User 3          70    80              90

For Manager -2 对于经理-2

            User Name    X      Y       Z
             User 1          10    20       30
             User 2          40    50       60
             User 3          70    80       90

I want actual 3 brand names as columns dynamically and not Brand-1, Brand-2, Brand -3. 我想要实际的3个品牌名称作为列动态而不是Brand-1,Brand-2,Brand -3。 I can hard code these brand names but as I said they can vary from manager to manager but at a time one manager. 我可以对这些品牌进行硬编码,但正如我所说,他们可能因经理而异,但同时也是一位经理。

Pivotting can be achieved in multiple ways, 透视可以通过多种方式实现,

1) using pivot function 2) using XML function 3) dynamic SQLs 4) using cursors 1)使用pivot函数2)使用XML函数3)动态SQL 4)使用游标

Assuming you are using Oracle SQL database all the above can be applicable please investigate more on the above. 假设您正在使用Oracle SQL数据库,以上所有内容都适用,请在上面进行更多调查。 If its otherwise few of the above will be applicable along with other options with respect to your database tool. 如果上述其他几项将适用于您的数据库工具的其他选项。

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

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