【问题标题】:sql query to get value on maximum date comparing current record datesql查询以获取比较当前记录日期的最大日期的值
【发布时间】:2017-10-16 10:00:51
【问题描述】:

我有 2 张桌子 Table1 有字段

childid, ondate, 点 1 2017 年 1 月 31 日 50 1 2017 年 2 月 28 日 77 1 2017 年 3 月 31 日 25

Table2 有字段

childid,programid,从日期 1 1 01/01/2017 1 2 01/03/2017

Table2 指定孩子在 01/01/2017 到 01/03/2017 期间处于 programid 1 中,之后他处于 programid 2 中。 所以我的结果应该是这样的

childid, ondate, 点 Programid 1 2017 年 1 月 31 日 50 1 1 28/02/2017 77 1 1 2017 年 3 月 31 日 25 2

请帮忙

【问题讨论】:

    标签: mysql sql visual-foxpro


    【解决方案1】:

    注意:此答案适用于 MySQL。

    这有点棘手。我认为关联子查询是最简单的方法:

    select t1.*, 
           (select t2.programid
            from table2 t2
            where t2.childid = t1.childid and
                  t2.fromdate <= t1.ondate
            order by t1.ondate desc
            limit 1
           ) as programid
    from table1 t1
    order by t1.ondate desc;
    

    这保证在table1 的任何给定日期只有一个程序(每个孩子)。

    【讨论】:

    • @Santosh 所以不要使用“已停止使用的以数据为中心、面向对象、过程化的编程语言”
    • @Strawberry 。 . .我什至没有注意到 Foxpro 标签。
    • 感谢它对我有用。只有我在上面的查询中添加的东西是 order by t1.ondate desc
    • @Strawberry,限制 1 在 MSSQL 中也不起作用。所以不要也使用 MSSQL 吗?哈哈。
    【解决方案2】:

    试试这个:

    SELECT t1.childid, t1.ondate, t1.points, t2.programid
    FROM table1 as t1
    INNER JOIN table2 as t2  on t1.chilid = t2.childid
                            and t2.fromdate <= t1.ondate;
    

    只需使用t2.fromdate &lt;= t1.ondate 连接两个表。

    【讨论】:

      【解决方案3】:

      如果查询需要与 VFP 兼容,则可以是:

      Select tb1.*, tb2.programid ;
          FROM table1 tb1 ;
          inner Join (;
          SELECT *, ;
          NVL((Select Min(fromdate) ;
          from table2 t1;
          WHERE t1.childid=t2.childid And ;
                t1.fromdate > t2.fromdate),Date(9999,12,31)) As toDate ;
          FROM table2 t2 ;
          ) tb2 ;
          ON tb1.childid = tb2.childid And ;
             tb1.ondate >= tb2.fromdate And ;
             tb1.ondate < tb2.toDate
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 1970-01-01
        相关资源
        最近更新 更多