首页 \ 问答 \ 在SQL中获取日期范围(Get Date Ranges in SQL)

在SQL中获取日期范围(Get Date Ranges in SQL)

我有一张看起来像下面的表

Price   | DateTime
--------+-------------
100     | 22/01/2016
210     | 23/01/2016
110     | 24/01/2016
10      | 25/01/2016
20      | 26/01/2016

30      | 13/03/2016
40      | 14/03/2016
50      | 15/03/2016
60      | 16/03/2016

现在我们可以看到它有两个日期范围:

  1. 22/01/2016 - > 26/01/2016
  2. 2016年3月13日 - > 16/032016

我如何查询我的数据库以获得上述结果,即我所描述的数据范围? 数据可以按日期排序,但如何获得范围


I have a table that look something like follows

Price   | DateTime
--------+-------------
100     | 22/01/2016
210     | 23/01/2016
110     | 24/01/2016
10      | 25/01/2016
20      | 26/01/2016

30      | 13/03/2016
40      | 14/03/2016
50      | 15/03/2016
60      | 16/03/2016

Now we can see there are two date ranges in it:

  1. 22/01/2016 -> 26/01/2016
  2. 13/03/2016 -> 16/032016

How can I query my database to get the above results, i.e the data ranges that I have described? The data can be ordered by date but how to get the range


原文:https://stackoverflow.com/questions/46708883
更新时间:2023-09-10 07:09

最满意答案

Oracle通常不会识别嵌套子查询中多于一个级别的表别名(或其他); 从文档

当嵌套子查询从引用子查询上一级的父语句的表引用列时,Oracle执行相关子查询。 [...]对于由父语句处理的每一行,概念上相关的子查询将被评估一次。

请注意“单层”部分。 因此,在嵌套子查询中,您的qm别名无法识别,因为它与qm别名的定义相距两级。 (如果你没有别名,原始表名也会发生同样的事情 - 这不是专门用于别名的)。

当你修改你的查询时,只需select qm.mdl_mdl_id as Vehicle_colour - 或者它的一个有效版本,或许(select qm.mdl_mdl_id from dual) as Vehicle_colour - 你删除了嵌套,并且qm现在只有一个级别定义在查询的主体中,因此得到了认可。

您在第一个嵌套子查询中对md引用可能不会被识别,但解析器往往会向后排序,所以它首先看到qm问题; 尽管可能重写查询会使其有效:

但是,优化器可能会选择将查询重写为联接,或者使用其他一些技术来制定语义等价的查询。

你也可以添加提示来鼓励,但最好不要依赖于此。

但是你不需要嵌套子查询,你可以在每个顶级子查询中加入:

select (
        select mc2.make_description
        from model_colours@dblink1 mc1,
            make_colours@dblink1 mc2  
        where mc2.makc_id = mc1.makc_makc_id
        and to_char(mc1.mdc_id) = md.allocate_vehicle_colour_id
    ) as colour,
    (
        select mc2.make_description
        from model_colours@dblink1 mc1,
            make_colours@dblink1 mc2
        where mc2.makc_id = mc1.makc_makc_id
        and mc1.mdl_mdl_id = qm.mdl_mdl_id
    ) as vehicle_colour
from schema1.web_order wo,
...

我坚持使用旧式连接语法来匹配主查询,但您应该考虑用现代ANSI连接语法重写整个事物。 (我也删除了提到的流氓逗号@Serg,但在发布问题时,您可能只是在实际选择列表中忽略了其他列。)

通过连接到主查询中的make和model颜色表,可以完全避免子查询,可以两次处理单独的过滤条件,或者在列表达式中使用一些逻辑。 虽然一次一步,但...


Oracle usually doesn't recognise table aliases (or anything else) more than one level down in a nested subquery; from the documentation:

Oracle performs a correlated subquery when a nested subquery references a column from a table referred to a parent statement one level above the subquery. [...] A correlated subquery conceptually is evaluated once for each row processed by the parent statement.

Note the 'one level' part. So your qm alias isn't being recognised where it is, in the nested subquery, as it is two levels away from the definition of the qm alias. (The same thing would happen with the original table name if you hadn't aliased it - it isn't specifically to do with aliases).

When you modified your query to just have select qm.mdl_mdl_id as Vehicle_colour - or a valid version of that, maybe (select qm.mdl_mdl_id from dual) as Vehicle_colour - you removed the nesting, and the qm was now only one level down from it's definition in the main body of the query, so it was recognised.

Your reference to md in the first nested subquery probably won't be recognised either, but the parser tends to sort of work backwards, so it's seeing the qm problem first; although it's possible a query rewrite would make it valid:

However, the optimizer may choose to rewrite the query as a join or use some other technique to formulate a query that is semantically equivalent.

You could also add hints to encourage that but it's better not to rely on that.

But you don't need nested subqueries, you can join inside each top level subquery:

select (
        select mc2.make_description
        from model_colours@dblink1 mc1,
            make_colours@dblink1 mc2  
        where mc2.makc_id = mc1.makc_makc_id
        and to_char(mc1.mdc_id) = md.allocate_vehicle_colour_id
    ) as colour,
    (
        select mc2.make_description
        from model_colours@dblink1 mc1,
            make_colours@dblink1 mc2
        where mc2.makc_id = mc1.makc_makc_id
        and mc1.mdl_mdl_id = qm.mdl_mdl_id
    ) as vehicle_colour
from schema1.web_order wo,
...

I've stuck with old-style join syntax to match the main query, but you should really consider rewriting the whole thing with modern ANSI join syntax. (I've also removed the rogue comma @Serg mentioned, but you may just have left out other columns in your real select list when posting the question.)

You could probably avoid subqueries altogether by joining to the make and model colour tables in the main query, either twice to handle the separate filter conditions, or once with a bit of logic in the column expressions. Once step at a time though...

相关问答

更多
  • Oracle通常不会识别嵌套子查询中多于一个级别的表别名(或其他); 从文档 : 当嵌套子查询从引用子查询上一级的父语句的表引用列时,Oracle执行相关子查询。 [...]对于由父语句处理的每一行,概念上相关的子查询将被评估一次。 请注意“单层”部分。 因此,在嵌套子查询中,您的qm别名无法识别,因为它与qm别名的定义相距两级。 (如果你没有别名,原始表名也会发生同样的事情 - 这不是专门用于别名的)。 当你修改你的查询时,只需select qm.mdl_mdl_id as Vehicle_colour ...
  • 我终于找到了问题所在。 在查看每个查询的结果后,我意识到空值正在影响结果。 我通过排除空值来更新我的非相关子查询。 我更新的非相关子查询工作原理如下: - 非相关子查询 SELECT * FROM hr.bc_products p WHERE p.sku NOT IN (SELECT ol.sku FROM hr.bc_orderlines ol WHERE ol.sku IS NOT NULL); 希望这将有助于某人在将来避免这个问题。 I finally figured out what the is ...
  • 你的任务是一个经典的白嘴鸦问题的例子。 它不能在SQL有效解决。 有一些简单的算法可以很好地工作,如果你的工作人员可能具有所需的技能(即一个非技术工人是一种罕见的例外情况而不是规则)。 但是,您最好使用SQL来检索限制,即哪些用户适合(或不适合)哪些项目,并将它们提供给启发式算法。 Your task is a classical example of rooks problem. It cannot be efficiently solved in SQL. There are some simple a ...
  • 嗯,首先它没有性能问题。 它就是这样,并且考虑到硬件和数据库结构的性能限制,它将尽可能地执行。 至于什么是有用的,它只是一种表达特定逻辑条件的方式。 Well, firstly it doesn't have a performance issue. It is what it is, and it will be executed as well as possible given the performance constraints of the hardware and database struc ...
  • 不确定我是否理解你想要做什么,但是删除子查询怎么样? SELECT "60+ DAYS", "30-60 DAYS", "7-30 DAYS", ("60+ DAYS" + "30-60 DAYS" + "7-30 DAYS") as "TOTAL", ... Not sure if I understand what you are trying to do, but what about removing the subquery? SELECT "60+ DAYS", " ...
  • 我在评论中提到你可以将两个查询一起加入......我会尝试复制这个以确保它有效..但是你的日期格式是关闭的,我没有时间将它们全部格式化。 SELECT t.orderdate, t.ordernum, t.saleschannel, t.sku, t1.expectedship FROM ( SELECT b.orderdate, b.ordernum, b.saleschannel, b.sku, s.expected ...
  • 弄清楚了。 Core.Property propAlias = null; baseQuery.JoinAlias(parent => parent.Properties, () => propAlias) .Where(() => propAlias.PropertyClass == sortByProperty); var query = baseQuery.OrderBy(() => propAlias.Value); Figured it out. Core.Property propAl ...
  • 问题出在您的数据中。 如果我理解正确,你想知道结果中是否有这样的行哪个日期更大,那么患者约会。 如果没有找到这样的行,那就没问题。 如果是这样,您的查询看起 您可以直接选择不正确的数据: SELECT * FROM Patients p CROSS APPLY ( SELECT MAX(ModifiedAt) AS ModifiedAt FROM ResultsStored rs ...
  • 尝试这个 : SELECT f.fundname, SUM(i.price) FROM fund f JOIN items i ON i.fundid = f.id GROUP BY f.fundname Try this : SELECT f.fundname, SUM(i.price) FROM fund f JOIN items i ON i.fundid = f.id GROUP BY f. ...
  • 这将有助于更好地了解尝试实现的目标,以用户域术语而不是SQL表示。 此外,没有给出被查询数据的整个范围和结构,但可能包括确定性能所涉及的关系。 首先,有这个Results表变量,它有自己的派生。 这种技术可能存在风险,因为它构建在一个隐式临时表中,这通常是一个去优化器。 这就像你试图为查询优化器指定策略。 看起来您只需要聚合查询中的一个最大值,该值应该是可优化的。 实际上,优化甚至不应该只有17K记录的问题。 你能否以下列形式重述: SELECT MAX(Value) FROM some-aggregate ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)