【问题标题】:How can I get the month that is not yet updated in SQL by inserting another row on every update?如何通过在每次更新时插入另一行来获取 SQL 中尚未更新的月份?
【发布时间】:2015-08-19 05:31:25
【问题描述】:

我有一张表,其中包含需要每月更新的不同交易记录。成功更新特定月份的记录后,它将向该表插入一条新记录,以表明它已经更新。我们以这个例子为例。

**date_of_transaction**   **type**   
2015-04-21              1 //A deposit record
2015-04-24              2 //A withdrawal record
2015-04-29              1
2015-04-30              2
2015-04-30              3 //3, means an update record
2015-05-14              1
2015-05-22              1
2015-05-27              2
2015-05-30              2
2015-06-09              1
2015-06-12              2
2015-06-17              2
2015-06-19              2

假设今天是 2015 年 7 月 23 日,我只能得到比当前月份低一个月的数据,所以我能得到的数据只有 6 月及以下的记录。

如您所见,由于type属性中的'3',在4月份执行了更新,但是在5月和6月,没有发生更新,我怎样才能得到月份还没更新?

【问题讨论】:

  • 不清楚“获取月份”是什么意思。您需要有一个月,其中没有类型 3 的记录?
  • 例如,五月和六月没有更新,因为如果我根据月份对日期进行分组,五月和六月没有包含 type = '3' 的行,那么 sql 应该我需要写信返回 5 月和 6 月,因为没有更新。

标签: mysql sql date


【解决方案1】:

这将返回几个月,其中没有 type=3 行

SELECT MONTH([trans-date]) FROM [table] GROUP BY MONTH([trans-date]) HAVING MAX([trans-type])<3

注意:如果 3 不是列中的最大值,这将不起作用

【讨论】:

    【解决方案2】:

    我的方法是先查找所有月份,然后查找记录已更新的月份。然后从所有没有更新记录的月份中只选择那些月份(A set减操作)。

    Mysql 查询会是这样的

    select extract(MONTH,data_of_transaction) from your_table_name where month not in (select extract(MONTH,data_of_transaction) from table where type=3);

    【讨论】:

      【解决方案3】:

      你可以试试这个;

      select * 
      from tbl
      where date_of_transaction < 'July 23, 2015'
      and
      date_format(date_of_transaction, '%M-%Y') in (
          select 
              date_format(date_of_transaction, '%M-%Y')
          from tbl
          group by date_format(date_of_transaction, '%M-%Y')
          having max(type) != 3
      )
      

      date_format(date_of_transaction, '%M-%Y') 将考虑month-year 并过滤具有type = 3 的数据。

      【讨论】:

      • 感谢您的回答! :)
      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 2014-04-02
      • 2023-01-23
      • 2012-06-16
      • 2016-12-12
      相关资源
      最近更新 更多