【问题标题】:SQL Query for getting data from different columns of different rows用于从不同行的不同列获取数据的 SQL 查询
【发布时间】:2022-01-17 02:34:21
【问题描述】:

我有如下数据集:

VN FNAME SEG         STARTTIME               ENDTIME          F1  DIS  F2 
5   try   1    09-DEC-21 10.00.00 PM  09-DEC-21 11.05.00 PM   0    2    1
1   eat   1    09-DEC-21 11.00.00 PM  09-DEC-21 11.59.59 PM   1   15    1 
5   sit   1    09-DEC-21 11.30.00 PM  09-DEC-21 11.59.59 PM   0   21    1
1   eat   2    10-DEC-21 12.00.00 AM  10-DEC-21 02.00.00 AM   1   15    1
5   sit   2    10-DEC-21 12.00.00 AM  10-DEC-21 04.00.00 AM   0   21    1
9   fly   1    10-DEC-21 01.00.00 AM  10-DEC-21 04.30.00 AM   1   50    1
4   say   1    10-DEC-21 05.00.00 AM  10-DEC-21 06.30.00 AM   0   25    1

使用上述数据集,我想获取具有唯一 FNAME 的记录,其中 F1F2 均为 1,但 STARTTIME 显示 STARTTIME,其中 SEG = 1ENDTIME 显示 ENDTIME其中SEG = max(SEG) 代表FNAME。所以基本上我正在查看的结果是:

VN FNAME      STARTTIME              ENDTIME             DIS  
1   eat   09-DEC-21 11.00.00 PM  10-DEC-21 02.00.00 AM    15
9   fly   10-DEC-21 01.00.00 AM  10-DEC-21 04.30.00 AM    50 

如何使用 SQL 查询来实现这一点?我正在使用的数据库是 Oracle。

任何帮助表示赞赏。非常感谢。

【问题讨论】:

  • 你自己试过 SQL 吗?
  • @Nathan_Sav 事实上我有。我尝试使用 rowid 解决它,也尝试了 rank() 但由于我是初学者,所以我迷路了,找不到出路。我可以使用 PL/SQL 来做到这一点,但使用 SQL 查询对我来说似乎很困难。我可以从同一行获取 START 和 ENDTIMES,但用例是这样的,即 STARTTIME 应该是 SEG 最小的那个(即 1),而 ENDTIME 应该是 FNAME 的 SEG 最大的那个。
  • 您是否尝试过使用countmax 并使用having count(*)=1 进行分组
  • @Nathan_Sav 不,我没有尝试过。你能帮忙查询一下吗?
  • select t.fname, (select t2.starttime from table1 as t2 where t2.fname=t.fname and t2.seg=1) as start_time, (select max(t3.endtime) from table1 as t3 where t3.fname=t.fname) as end_time, from table1 as t where t.f1=1 and t.f2=1 group by fname having count(*)=1我没测试过

标签: sql oracle


【解决方案1】:

类似的,使用grouing 和子查询。将 count(*) 设为 1 将显示名称的 1 个实例,其中 F1 和 F2 为 1。

select t.fname, 
(select t2.starttime from table1 as t2 where t2.fname=t.fname and t2.seg=1) as start_time, 
max(t.endtime) as end_time
 from table1 as t 
where t.f1=1 and t.f2=1 
group by t.fname 
having count(*)=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2018-12-31
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多