SQL查询在同一列

时间:2015-12-24 16:14:49

标签: sql database oracle

之前询问的面试问题。

给定一个包含boxName和value列的表,找到每个框的音量。 值字段具有立方体的长度,bredth和高度。我需要将所有树的尺寸相乘。

如果需要计算总和,我可以使用 groupby ,但这里需要产品

box1 = 12*13*1  = 156
box2 = 1*23*6   = 138
box3 = 12*1*20  = 240

+---------+-------+
| boxName | value |
+---------+-------+
| box1    |    12 |
| box1    |    13 |
| box1    |     3 |
| box2    |     1 |
| box2    |    23 |
| box2    |     6 |
| box3    |    12 |
| box3    |     1 |
| box4    |    30 |
+---------+-------+

2 个答案:

答案 0 :(得分:2)

试试这个

select EXP(SUM(LN(value))) As Product_val ,boxName
from yourTable
Group by boxName

注意: value <= 0 LOG将失败。

当你有值&lt; = 0时,请使用它。

SELECT
    boxName,
    CASE
       WHEN MinVal = 0 THEN 0
       WHEN Neg % 2 = 1 THEN -1 * EXP(ABSMult)
       ELSE EXP(ABSMult)
    END
FROM
    (
    SELECT
       boxName, 
       --log of +ve row values
       SUM(LN(ABS(NULLIF(Value, 0)))) AS ABSMult,
       --count of -ve values. Even = +ve result.
       SUM(SIGN(CASE WHEN Value < 0 THEN 1 ELSE 0 END)) AS Neg,
       --anything * zero = zero
       MIN(ABS(Value)) AS MinVal
    FROM
       yourTable
    GROUP BY
       boxName
    ) foo

参考此answer

答案 1 :(得分:1)

如果您知道每个方框的3个维度恰好有3行,您可以使用row_number()解析函数唯一标识3个维度,然后使用max(case ...)提取3个维度并乘以它们:

select boxName,
       max(case when rn = 1 then value end) *
       max(case when rn = 2 then value end) *
       max(case when rn = 3 then value end) as volume
  from (select t.*,
               row_number() over (partition by t.boxName order by null) as rn
          from yourTable t)
 group by boxName