【问题标题】:Collect Maximum month data收集最大月份数据
【发布时间】:2015-12-10 07:19:28
【问题描述】:

我需要从数据库中收集数据 基于上个月的创建。

就我而言

一个。 month_val 是单个月份

b. cur_month 是最后更新的月份

每个月(cur_month)我的用户可以更新任何月份(month_val)的数据。

示例输出:

查询应该只返回上个月的数据。

在 1 月 (cur_month 1) 我添加了 Jan、Feb 的数据,即 month_val 1,2

在二月(cur_month 2)我添加了二月,三月的数据,即month_val 2,3

...

在 12 月 (cur_month 12) 我添加了 Mar 的数据,即 month_val 3。

基于此存储的数据。我必须根据 cur_month 收集最新(标记为绿色)month_val

希望我已经清楚地解释了我的问题。

我是这样尝试的

SELECT * FROM proj_duration_map where cur_month=max(cur_month)

不好用

【问题讨论】:

  • 您使用的是哪个数据库,MySQL 还是 SQL Server?
  • 你的意思是查询可以检索到最新的cur_month吗?例如,year_val & cur_month = '2016-12'。
  • 这似乎是日期列策略的错误选择
  • “last_updated”字段有什么用?您还想要考虑或不考虑 year_val 的最大 cur_month 的结果吗?
  • last_updated 仅用于记录目的。我每年都需要 cur_month

标签: mysql sql-server


【解决方案1】:

我认为你应该GROUP BY 4 第一列。

MSSQL中,可以使用ROW_NUMBER选择MAXMONTH

SELECT * FROM
(
   SELECT
      *,
      ROW_NUMBER() OVER(PARTITION BY pid, week_val, month_val, year_val 
                        ORDER BY cur_month DESC) AS RN
   FROM proj_duration_map
) AS A
WHERE RN = 1 --choose MAX cur_month (ORDER DESC)

MySQL 中,您可以使用COUNT 代替ROW_NUMBER

SELECT * FROM (
   SELECT A.pid, A.week_val, A.month_val, A.year_val, A.cur_month,
          Count(*) as RN
   FROM proj_duration_map A
   INNER JOIN proj_duration_map B
      ON A.pid = B.pid
         AND A.week_val = B.week_val
         AND A.month_val = B.month_val
         AND A.year_val = B.year_val
         AND A.cur_month >= B.cur_month
   GROUP BY A.pid, A.week_val, A.month_val, A.year_val, A.cur_month
) AS C
WHERE RN = 1

【讨论】:

  • 如果他使用MySQL,不支持解析函数partition by
  • 您可以 GROUP BY month_val, year_val
  • 以上 mysql 查询不在我的数据库上运行
  • @Nguyễn Hải Triều 你解决了我的问题。您的答案做了一些小改动。您的查询错过了一个逗号,它返回了最小的 cur_months。我已经纠正了。非常感谢您的帮助
【解决方案2】:
 SELECT month_val, year_val, cur_month FROM proj_duration_map
  where cur_month=max(cur_month)
   group by month_val, year_val, cur_month 

SELECT 中的字段列表必须与 GROUP BY 相同。

【讨论】:

  • 您的查询仅返回 12 月 (12) 月份的数据,我需要所有最新数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 2011-10-17
  • 2015-03-28
  • 1970-01-01
相关资源
最近更新 更多