【问题标题】:Oracle SQL - Returning multiple row results into one single row using LAG or LEADOracle SQL - 使用 LAG 或 LEAD 将多行结果返回到一行
【发布时间】:2018-10-30 11:12:46
【问题描述】:

我试图弄清楚如何为多行结果返回 1 行。

目前我的代码如下所示:

select x.Reference,
x.date "Date1",
x.char "Char1",
lead(x.date, 1) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Date2",
lead(x.char, 1) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Char2",
lead(x.date, 2) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Date3",
lead(x.char, 2) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Char3"

from tbl x

该表对于每个 x.Reference 都有多个条目。对于每个 x.Reference 的第一行,该行返回所需的结果。但是,正如预期的那样,它会继续为找到的每个 x.reference 输出一行。我正在尝试找到一种方法来限制这些额外行的输出,因为第一行已经有我需要的数据。

提前致谢。

【问题讨论】:

    标签: sql oracle lag lead


    【解决方案1】:

    嗯,你可以使用row_number()

    with x as (
          select x.Reference, x.date as "Date1", x.char as "Char1",
                 lead(x.date, 1) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Date2",
                 lead(x.char, 1) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Char2",
                 lead(x.date, 2) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Date3",
                 lead(x.char, 2) OVER (PARTITION BY x.Reference ORDER BY x.date) as "Char3",
                 row_number() over (partition by x.Reference order by x.date) as seqnum
          from tbl x
         )
    select x.*
    from x
    where seqnum = 1;
    

    【讨论】:

    • 感谢 Gordon,这正是我一直在寻找的,并且在未来会非常有用。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多