如何附加具有最大值和最小值的列?

时间:2018-07-09 12:09:16

标签: sql oracle

说我有一个表“ A”,如下所示:

     ID |   Quantity
------------------------
     1  |     3333
     1  |     4444
     1  |     5555
     2  |     2344

我要创建一个新表,如下所示:

     ID |   Quantity   |  Max(Quantity)  |   Min(Quantity)
-----------------------------------------------------------
     1  |     3333     |     5555        |     3333
     1  |     4444     |     5555        |     3333 
     1  |     5555     |     5555        |     3333
     2  |     2344     |     2344        |     2344

(针对“ ID”计算最大值和最小值)

我该如何编码?

3 个答案:

答案 0 :(得分:4)

使用分析功能:

select id, quantity,
       max(quantity) over (partition by id) as max_quantity,
       min(quantity) over (partition by id) as min_quantity
from t;

答案 1 :(得分:0)

尝试以下操作:

select 
    ID,
    Quantity,
    B.Max_Quantity,
    B.Min_Quantity
From
    A
LEFT OUTER JOIN 
(
    select
      ID,
      MAX(Quantity) as Max_Quantity,
      MIN(Quantity) as Min_Quantity
    From
      A
    Group by
      ID
) B ON B.ID = A.ID

答案 2 :(得分:0)

选择编号,数量 从T 数量=(从t中选择max(数量)) 和数量=(从t中选择最小值(数量));