Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 难以找到每个月的最大值_Sql - Fatal编程技术网

Sql 难以找到每个月的最大值

Sql 难以找到每个月的最大值,sql,Sql,我相信这很简单,但我一直坚持下去。我有一张这样的桌子: Month Period Value May 2013 3 e May 2013 2 k May 2013 1 l April 2013 5 z April 2013 4 w April 2013 3 t April 2013 2 f April 2013 1 j 我想找到每个月最高时段的值。对于此数据,2013年5月为

我相信这很简单,但我一直坚持下去。我有一张这样的桌子:

Month      Period  Value
May 2013   3       e
May 2013   2       k
May 2013   1       l
April 2013 5       z
April 2013 4       w
April 2013 3       t
April 2013 2       f
April 2013 1       j

我想找到每个月最高时段的值。对于此数据,2013年5月为e,2013年4月为z。

您没有指定正在使用的RDBMS,但可以使用子查询获取每个月的
最大(周期)
,然后加入表以获取值:

select t1.month,
  t1.period,
  t1.value
from yourtable t1
inner join
(
  select max(period) period, month
  from yourtable
  group by month
) t2
  on t1.month = t2.month
  and t1.period = t2.period;

如果您的数据库具有窗口功能,则可以使用
row\u number()
获得结果:

select month, period, value
from 
(
  select month, period, value,
    row_number() over(partition by month order by period desc) rn
  from yourtable
) d
where rn = 1;

请参阅在大多数RDBMS中应该适用的通用SQL解决方案:

SELECT month, period, value
FROM   tbl t
WHERE  NOT EXISTS (
   SELECT 1 FROM tbl t1
   WHERE  t1.month = t.month
   AND    t1.period > t.period
   );
这是专为Postgres设计的,速度稍快一些:

SELECT DISTINCT ON (month)
       month, period, value
FROM   tbl t
ORDER  BY month, period DESC, value DESC;
我将
value DESC
添加到
ORDER BY
中,以在同样长的时间内打破联系。在这种情况下,您将获得值更大的行


如果您添加了另一个记录-月份:2013年5月,期间:3,值:f。现在,同一个月有多个值max(Period)。你希望结果是什么?你也有身份证吗?可以复制月份吗?哪个是您的RDBMS和版本?SQL Server 2012。很抱歉遗漏了这一点。我喜欢SQL Fiddle演示。谢谢