无法按日期获取最近的记录

时间:2019-02-01 13:50:14

标签: mysql

我已执行以下查询以获取最新记录,但它显示的是上个月的记录而不是最新记录。

#include <list>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

struct HalfEdge {
  int head;
  std::list<HalfEdge>::iterator opposite;
};

std::vector<std::vector<int>> SimpleCyclesFromEdges(
    const std::vector<std::pair<int, int>>& edges) {
  std::unordered_map<int, std::list<HalfEdge>> graph;
  for (const auto& edge : edges) {
    auto& first_neighbors = graph[edge.first];
    auto& second_neighbors = graph[edge.second];
    auto forward = first_neighbors.emplace(first_neighbors.begin());
    auto backward = second_neighbors.emplace(second_neighbors.begin());
    *forward = {edge.second, backward};
    *backward = {edge.first, forward};
  }
  std::vector<std::vector<int>> simple_cycles;
  for (auto& item : graph) {
    int v = item.first;
    std::unordered_set<int> on_stack;
    std::stack<int> stack;
    while (true) {
      if (on_stack.insert(v).second) {
        stack.push(v);
      } else {
        std::vector<int> cycle = {v};
        while (stack.top() != v) {
          cycle.push_back(stack.top());
          on_stack.erase(stack.top());
          stack.pop();
        }
        simple_cycles.push_back(std::move(cycle));
      }
      auto& neighbors = graph[v];
      if (neighbors.empty()) {
        break;
      }
      auto forward = neighbors.begin();
      v = forward->head;
      graph[v].erase(forward->opposite);
      neighbors.erase(forward);
    }
  }
  return simple_cycles;
}

我希望输出为:

Output I Want

但是它给我的输出是:

Output I Have

2 个答案:

答案 0 :(得分:0)

您必须对结果进行排序。在查询中,您应该使用order by。 删除max

SELECT t1.*
  FROM merchnat_tbl_sells_rc t1
  WHERE t1.S_Date = (SELECT TOP 1 t2.S_Date
                       FROM merchnat_tbl_sells_rc t2
                       WHERE t1.MID = 'MNJ'
                     ORDER BY t1.S_Date DESC)

答案 1 :(得分:-1)

使用存储为varchar的日期的简化示例。

drop table if exists t;
create table t(id int auto_increment primary key,dt varchar(10),merchant int);

insert into t (dt,merchant) values
('01-01-2019',1),('27-12-2018',1);

select t.* ,str_to_date(dt,'%d-%m-%Y') dtConvertd,
        (select max(str_to_date(dt,'%d-%m-%Y')) from t t1 where t1.merchant = t.merchant) maxdt
from t 
where str_to_date(t.dt,'%d-%m-%Y') = (select max(str_to_date(dt,'%d-%m-%Y')) from t t1 where t1.merchant = t.merchant)

+----+------------+----------+------------+------------+
| id | dt         | merchant | dtConvertd | maxdt      |
+----+------------+----------+------------+------------+
|  1 | 01-01-2019 |        1 | 2019-01-01 | 2019-01-01 |
+----+------------+----------+------------+------------+
1 row in set (0.00 sec)