【问题标题】:how to get data from min - max joining two columns from same table如何从 min - max 中获取数据,将同一表中的两列连接起来
【发布时间】:2021-10-27 22:13:57
【问题描述】:
select s1.name,min(s1.start_time),max(s2.end_time),
round(((max(s2.end_time) - min(s1.start_time)))*24)
from My_table s1,My_table s2
where (s1.process in ('abcd') and month like '%1708021%') and 
(s2.process in ('xyz' and month like '%1708021%'))
group by s1.process_name;

PROCESS_NAME    MIN(S1.START_TIME)  MAX(S2.END_TIME)    ROUND(((MAX(S2.END_TIME)-MIN(S1.START_TIME))))
alert17 18-aug-2021 07:49:45 PM 20-aug-2021 12:01:09 PM 40

如果我在上面运行查询,我的表中有 31 个条目,我会从中获得正确的数据,即进程 start_time 和 end_time 以及差异。

但如果我在月份级别运行它,那么它会给我错误的数据

select s1.name,min(s1.start_time),max(s2.end_time),
round(((max(s2.end_time) - min(s1.start_time)))*24)
from My_table s1,My_table s2
where (s1.process in ('abcd') and month like '%08021%') and 
(s2.process in ('xyz' and month like '%08021%'))
group by s1.process_name;

Alert01 03-aug-2021 01:50:47 AM 27-aug-2021 06:16:30 AM 580
Alert02 03-aug-2021 08:10:57 PM 27-aug-2021 06:16:30 AM 562
Alert03 04-aug-2021 08:07:21 PM 27-aug-2021 06:16:30 AM 538
Alert04 06-aug-2021 03:42:51 AM 27-aug-2021 06:16:30 AM 507

你们能帮帮我吗?

【问题讨论】:

  • 很难理解你想要做什么。消除连接并将其替换为聚合函数中的过滤似乎会更清晰、更有效。你只按一列分组,所以我可能猜想连接不是你想要的。
  • @RohanDolas 。 . .我的建议:删除这个问题。问一个新问题。对您要完成的工作提供清晰的解释。提供样本数据和期望的结果。然后显示有效或无效的查询。

标签: sql max min


【解决方案1】:

您的逻辑可能存在错误。注意这之间的区别:

and (s2.process in ('xyz'   and month like '%1708021%'))

还有这个:

and (s2.process in ('xyz')   and month like '%1708021%')

第二种形式很可能是你想做的。

我怀疑这会影响您认为产生正确结果的查询和您认为唯一有问题的其他查询。

另外,请注意以下事项。

您已选择name,但已按process_name 分组。这可能是一个函数依赖问题,在标准 SQL 方面会被认为是无效的。

有些数据库会忽略这种错误(如果它真的是 FD 错误)。没有完整的细节很难说。

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2021-06-21
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多