如何通过形成查询来获取数据?

Posted

技术标签:

【中文标题】如何通过形成查询来获取数据?【英文标题】:How do I get data by forming query? 【发布时间】:2017-10-31 06:13:11 【问题描述】:
table data:
  sno  data
    1  a
    2  b
    3  c
    5  d
    6  e
    8  f

result is :

l-side    r-side
a           b
c           null
d           e
null        f

我已经尝试过领先和滞后..

  select sno,
    lead(data,1) over(partition by data order by sno RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) as l-side,
    lag(data,1) over(partition by data order by sno RANGE BETWEEN 2 PRECEDING AND 1 FOLLOWING) as r-side
    from table

但它给出了不同的我所需要的。根据我的结果形成查询。

【问题讨论】:

【参考方案1】:

我的解决方案:

with t as (
  select 1 as sno, 'a' as data from dual
  union all
  select 2 as sno, 'b' as data from dual
  union all
  select 3 as sno, 'c' as data from dual
  union all
  select 5 as sno, 'd' as data from dual
  union all
  select 6 as sno, 'e' as data from dual
  union all
  select 8 as sno, 'f' as data from dual
)
,
inum as (
  select level as s1, level+1 as s2 from dual
  where mod(level,2) = 1
  connect by level <= (select max(sno) from t)
)

select t.data as l_side, t1.data as r_side
from inum left join t on inum.s1 = t.sno
          left join t t1 on inum.s2 = t1.sno
order by s1

输出:

 L_SIDE R_SIDE
    a   b
    c   - 
    d   e
    -   f

【讨论】:

如果 max 是一个不能除法的数,你会为假【参考方案2】:

试试这个。

WITH ut 
     AS (SELECT t.*, 
                rownum rn 
         FROM   yourtable t) 
SELECT a.data, 
       b.data 
FROM   (SELECT data, 
               rn 
        FROM   ut 
        WHERE  MOD(sno, 2) = 1) a 
       FULL OUTER JOIN (SELECT data, 
                               rn 
                        FROM   ut 
                        WHERE  MOD(sno, 2) = 0) b 
                    ON a.rn + 1 = b.rn 
ORDER  BY a.rn; 

【讨论】:

以上是关于如何通过形成查询来获取数据?的主要内容,如果未能解决你的问题,请参考以下文章

无法通过 API 查询 BigQuery 数据集来获取数据

使用嵌套查询 REST API 获取请求

如何通过查询获取 cosmosDB 中的数据库或容器大小?

eggjs 怎么实现获取账单列表接口并且实现列表数据分页查询功能?

Lambda查询抛出对象不包含错误,同时通过`MOQ`设置来获取动态类型的数据

如何在PHP中获取MYSQL数据库返回的数据的行数?