LAST_DAY函数在MySQL中无法正常工作。

huangapple go评论75阅读模式
英文:

LAST_DAY function in mysql is not working

问题

以下是翻译好的部分:

我在mysql中使用LAST_DAY()函数来获取每个月每个客户的最后一天的数值。我使用的是mysql 8.0版本。有人可以帮助我吗?示例表格如下:

示例代码:

select customer_id, LAST_DAY(txn_date) AS months, txn_type, txn_amount 
   from data_bank.customer_transactions
   group by customer_id, months
   order by customer_id

从上面的代码中,这是我得到的结果:

预期结果:

customer_id   months     txn_type  txn_amount
      1      2020-01-31   deposit       312
      1      2020-03-31   purchase      664
英文:

Here I am using LAST_DAY() function to get last day of values from each month for each customer in mysql.
I am using mysql 8.0 version.
Could anyone please help me with this.
Sample table example:

LAST_DAY函数在MySQL中无法正常工作。

sample code:

select customer_id, LAST_DAY(txn_date) AS months, txn_type, txn_amount 
   from data_bank.customer_transactions
   group by customer_id, months
   order by customer_id

From the above code this is the results I have obtained :

LAST_DAY函数在MySQL中无法正常工作。

Expected results:

customer_id   months     txn_type  txn_amount
      1      2020-01-31   deposit       312
      1      2020-03-31   purchase      664

答案1

得分: 1

以下是翻译好的内容:

你假设因为你按照月份的最后一天进行分组,它会返回其他列的最新行的值。这并不是事实。在一个列中返回的值与应用于其他列的函数毫无关系。

阅读这个链接:

然后使用类似这样的方法来返回每个日历月的最新行...

WITH
  partitioned AS
(
  SELECT
    *,
    ROW_NUMBER()
      OVER (
        PARTITION BY customer_id, LAST_DAY(txn_date) 
            ORDER BY txn_date DESC
      )
        AS month_row_id
  FROM
    data_bank.customer_transactions
)
SELECT
  *
FROM
  partitioned
WHERE
  month_row_id = 1
英文:

You're assuming that because you group by the last day of the month, it will return the latest row's values for the other columns. That's not the case. The values returned in one column have nothing to do with the functions applied to other columns.

Read this:

Then use something like this to return the latest row per calendar month...

WITH
  partitioned AS
(
  SELECT
    *,
    ROW_NUMBER()
      OVER (
        PARTITION BY customer_id, LAST_DAY(txn_date) 
            ORDER BY txn_date DESC
      )
        AS month_row_id
  FROM
    data_bank.customer_transactions
)
SELECT
  *
FROM
  partitioned
WHERE
  month_row_id = 1

huangapple
  • 本文由 发表于 2023年4月13日 17:54:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定