基于sql中多列的条件过滤

时间:2018-01-11 21:46:35

标签: sql db2

我有一张包含以下列的表格&数据:

ID    NAME    Amount              Date
53    GSG    -2,695,190,307.57    1/22/2018
53    GSG    -2,698,190,307.57    1/23/2018
77    GSG    -2,508,853,140.14    1/22/2018
77    GSG    -2,508,303,140.14    1/23/2018
76    GSG    -2,479,894,820.77    1/23/2018
53    MLG    -2,443,081,761.81    1/23/2018
53    MLG    -2,405,497,472.79    1/22/2018
67    GSG    -2,164,848,916.29    1/23/2018
66    GSG    -2,160,447,589.23    1/22/2018
66    GSG    -2,160,447,589.23    1/23/2018
76    MLG    -2,147,093,992.33    1/23/2018

我正在寻找的输出是每当我们为特定场景连续两个日期时,我们需要比较金额以及我们有最大金额的日期,我想将该记录显示为结果。预期的结果集应如下所示:

ID    NAME    Amount              Date
53    GSG    -2,698,190,307.57    1/23/2018
77    GSG    -2,508,853,140.14    1/22/2018
76    GSG    -2,479,894,820.77    1/23/2018
53    MLG    -2,443,081,761.81    1/23/2018
67    GSG    -2,164,848,916.29    1/23/2018
66    GSG    -2,160,447,589.23    1/22/2018
76    MLG    -2,147,093,992.33    1/23/2018

我尝试了case语句,这是我拥有的SQL:

select hdc1.ID, hdc1.name, 
    case when hdc1.amount < hdc2.amount
        then hdc1.amount
        else hdc2.amount
    end as Final_amount,
    Case when hdc1.amount < hdc2.amount
        then hdc1.date
        else hdc2.date
    end as forecast_date,
from Hori_dmnd_cmo hdc1, Hori_dmnd_cmo hdc2
where hdc1.date = date(hdc2.date - 1 day)
    and hdc1.id = hdc2.id
    and hdc1.name = hdc2.name

1 个答案:

答案 0 :(得分:0)

你的逻辑似乎在正确的轨道上,虽然我会使用join而不是, - 你会得到最小值而不是最大值。

这样做你想要的吗?

select hdc1.ID, hdc1.name, 
       (case when hdc1.amount >= hdc2.amount
             then hdc1.amount
              else hdc2.amount
        end) as Final_amount,
       (case when hdc1.amount >= hdc2.amount
             then hdc1.date
             else hdc2.date
        end) as forecast_date,
from Hori_dmnd_cmo hdc1 join
     Hori_dmnd_cmo hdc2
     on hdc1.date = (hdc2.date - 1 day) and
        hdc1.id = hdc2.id
        hdc1.name = hdc2.name