SQL查询可从一列中获取最大值,但也保留不属于pf组的另一列

时间:2018-08-22 20:15:13

标签: sql oracle

我正在尝试获取v_id上w_cost的最大值,如果w_cost为Null,则取r_cost并列出下表中给出的结果。当group by位于v_id上以获取最大w_cost时,如何获取av_id?

s_id sg_id  r_cost  w_cost  av_id v_id
123  100    0.50    1.00    1     333
123  105    0.75    0       2     333
123  330    1.00    Null    3     888

最终结果应该是:

s_id v_id   w_cost  av_id
123  333     1.00   1
123  888     1.00   3

4 个答案:

答案 0 :(得分:0)

如果您的SQL支持分析功能,我会做这样的事情。

SELECT
  s_id,
  v_id,
  MAX(CASE WHEN w_cost IS NULL THEN r_cost ELSE w_cost END) OVER (PARTITION BY v_id) AS w_cost,
  av_id
FROM [YOUR_TABLE]

在此查询中,您无需按v_id分组。

希望有帮助

答案 1 :(得分:0)

像这样吗?

    for line in (file):
            #turn the first 5 characters into an object
            obj = eval (line[0:5]) 
            obj (line)

    def H0100(line)
          .....process line

    #Just point all the alternative to the one function
    H0101 = H0102 = H0103 = H0104 = H0105 = H0106 = H0107 = H0108 = H0109 = H0100

答案 2 :(得分:0)

从您的描述中我了解到的(不幸的是,您的示例是模棱两可的),可能是这样的:

SELECT S_ID,
       V_ID,
       W_COST,
       AV_ID
       FROM (SELECT S_ID,
                    V_ID,
                    COALESCE(W_COST, R_COST) W_COST,
                    AV_ID,
                    ROW_NUMBER() OVER (PARTITION BY V_ID
                                       ORDER BY COALESCE(W_COST, R_COST) DESC) RN
                    FROM ELBAT)
       WHERE RN = 1;

它得到一行,其中COALESCE(W_COST, R_COST)是所有V_ID中最高的。如果有更多行且最大值,则仅随机选择其中之一(如果需要平局,请将ROW_NUMBER()替换为RANK())。 COALESCE(W_COST, R_COST)使用R_COST,如果W_COST IS NULL,则使用W_COST。输出中名为W_COST的列还会显示COALESCE(W_COST, R_COST)的值(否则,如果直接显示W_COST,则在{{1 }}等于NULL

db<>fiddle

答案 3 :(得分:-1)

我想你想要

select t.*
from t
where (s_id, v_id, coalesce(w_cost, r_cost)) in (
          select s_id, v_id, max(coalesce(w_cost, r_cost))
          from t
          group by s_id, v_id
         );