如何基于多个最大日期列选择整行

时间:2019-06-27 09:50:43

标签: mysql sql

我要选择整个行,该行已被2个最大日期列过滤-

所以,如果我有一张桌子(供应):

D_id |O_id  | O_date    | Start_date| amount 
400  |1     | 2018-2-7  | 2018-4-7  | 500
401  |1     | 2019-8-2  | 2019-10-1 | 1500
402  |1     | 2019-8-2  | 2019-12-7 | 200
403  |2     | 2016-4-10 | 2016-5-7  | 100
404  |2     | 2018-12-1 | 2018-12-17| 50
405  |2     | 2018-12-1 | 2019-1-1  | 2500

因此,输出应按d_id分组,并显示具有最大O_date和最大start_date的整行

D_id |O_id  | O_date    |  Start_date | amount |
402  |1     | 2019-8-2  | 2019-12-7   | 200
405  |2     | 2018-12-1 | 2019-1-1    | 2500

我一直面临的问题是仅使用max和group by条件,SQL不匹配每一行的字段。

select max(O_DATE),
MAX(START_DATE),
D_ID,
AMOUNT,
O_ID
FROM SUPPLY
group by
O_ID;

4 个答案:

答案 0 :(得分:0)

以下查询应为您工作。按照您的逻辑,START_DATE对于这两种情况都是通用的,只有START_DATE之间的联接才可以解决问题。

SELECT * FROM SUPPLY A
INNER JOIN 
(
    SELECT O_ID,
    MAX(O_DATE) O_DATE,
    MAX(START_DATE) START_DATE
    FROM SUPPLY
    group by O_ID
)B 
ON A.O_ID = B.O_ID
AND A.START_DATE = B.START_DATE

答案 1 :(得分:0)

这是您要寻找的:

#include <chrono>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <sstream>

namespace fs = std::filesystem;

int main() {
    fs::file_time_type file_time = fs::last_write_time(__FILE__);
    std::time_t tt = decltype(file_time)::clock::to_time_t(file_time);
    std::tm *gmt = std::gmtime(&tt);
    std::stringstream buffer;
    buffer << std::put_time(gmt, "%A, %d %B %Y %H:%M");
    std::string formattedFileTime = buffer.str();
    std::cout << formattedFileTime << '\n';
}

答案 2 :(得分:0)

您可以通过将查询加入表格来做到这一点:

SELECT s.* 
FROM SUPPLY s INNER JOIN (
  SELECT 
    max(O_DATE) O_DATE,
    max(START_DATE) START_DATE
  FROM SUPPLY
  GROUP BY O_ID
) g ON g.O_ID = s.O_ID AND g.O_DATE = s.O_DATE AND g.START_DATE = s.START_DATE

或不存在:

SELECT s.* 
FROM SUPPLY s 
WHERE NOT EXISTS (
  SELECT 1 FROM SUPPLY
  WHERE O_ID = s.O_ID AND O_DATE > s.O_DATE AND START_DATE > s.START_DATE 
)

答案 3 :(得分:0)

O_DATE的优先级高于START_DATE

select *
from SUPPLY t
join (
    select MAX(t.START_DATE) maxSd, m.maxOd, t.O_ID
    from SUPPLY t
    join (    
        select max(O_DATE) maxOd, O_ID
        from SUPPLY
        group by O_ID
    ) m on m.O_ID = t.O_ID and m.maxOd = t.O_DATE;
    group by m.maxOd, t.O_ID
) m2 on m2.O_ID = t.O_ID and m2.maxOd = t.O_DATE and m2.maxSd = t.START_DATE

从8开始,可以使用WINDOW函数对其进行简化