在SQL中的其他列中查找具有最高值的列

时间:2015-09-23 15:37:38

标签: sql exacttarget

我有一个看起来像这样的表:



table,
th,
td {
  border: 1px solid black;

<table>
  <tr>
    <th>Customer</th>
    <th>Category 1</th>
    <th>Category 2</th>
    <th>Category 3</th>
    <th>Category 4</th>
  </tr>
  <tr>
    <td>aaaaa@aaa.com</td>
    <td>0</td>
    <td>563</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>bbbb@bbb.com</td>
    <td>33</td>
    <td>31</td>
    <td>38</td>
    <td>13</td>
  </tr>
  <tr>
    <td>cccc@ccc.com</td>
    <td>108</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>dddd@ddd.com</td>
    <td>0</td>
    <td>7</td>
    <td>0</td>
    <td>11</td>
  </tr>
</table>
&#13;
&#13;
&#13;

我正在尝试插入名为&#34; BestCategory&#34;的新列。这将显示它们之间具有最高值的类别的名称。

我尝试使用GREATEST,但我的系统不接受它。

你们能帮助我吗?

2 个答案:

答案 0 :(得分:1)

首先,您必须使用UNPIVOT来计算每行的maxValue

然后使用CASE选择BestCategory

<强> Sql Fiddle Demo

WITH maxValues as 
(
   select
     [Customer], Max(Amount) as TheMax
   from 
     Customer 
     UNPIVOT (Amount for AmountCol in 
              ([Category 1], [Category 2], [Category 3], [Category 4])) as unpvt
   group by [Customer]
)        
select 
    Customer.[Customer], [Category 1], [Category 2], [Category 3], [Category 4], 
    TheMax,
    Case 
        WHEN [Category 1] = TheMax THEN '[Category 1]'
        WHEN [Category 2] = TheMax THEN '[Category 2]'
        WHEN [Category 3] = TheMax THEN '[Category 3]'
        ELSE '[Category 4]'
    END  as BestCategory        
from Customer        
inner join maxValues
   on Customer.[Customer] = maxValues.[Customer]

输出

|      Customer | Category 1 | Category 2 | Category 3 | Category 4 | TheMax | BestCategory |
|---------------|------------|------------|------------|------------|--------|--------------|
| aaaaa@aaa.com |          0 |        563 |          0 |          0 |    563 | [Category 2] |
|  bbbb@bbb.com |         33 |         31 |         38 |         13 |     38 | [Category 3] |
|  cccc@ccc.com |        108 |          0 |          0 |          0 |    108 | [Category 1] |
|  dddd@ddd.com |          0 |          7 |          0 |         11 |     11 | [Category 4] |

答案 1 :(得分:0)

如果您想要“最大字段”中的列名,您可以使用此sqlfiddle中的想法example

选择每行值最大的列名

SELECT CASE 
        WHEN [category 1] > [category 2]
            AND [category 1] > [category 3]
            AND [category 1] > [category 4]
            THEN '[Category 1]'
        ELSE CASE 
                WHEN [category 2] > [category 1]
                    AND [category 2] > [category 3]
                    AND [category 2] > [category 4]
                    THEN '[Category 2]'
                ELSE CASE 
                        WHEN [category 3] > [category 1]
                            AND [category 3] > [category 2]
                            AND [category 3] > [category 4]
                            THEN '[Category 3]'
                        ELSE '[category 4]'
                        END
                END
        END
FROM customer