Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.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_Sql Server - Fatal编程技术网

Sql 如何在组内找到最高值?

Sql 如何在组内找到最高值?,sql,sql-server,Sql,Sql Server,我有一张表格,上面有很多申请表和日期。 我需要选择申请数量最多的年份和月份。 我的桌子看起来像: CisloSmlouvy | DatumZadosti 121651566 | 3-1-2010 07:23:21 121651516 | 7-5-2011 08:23:21 121551567 | 1-9-2010 09:25:21 121651562 | 3-5-2017 17:23:21 我想: Best year | Numb

我有一张表格,上面有很多申请表和日期。 我需要选择申请数量最多的年份和月份。 我的桌子看起来像:

 CisloSmlouvy | DatumZadosti
    121651566    | 3-1-2010 07:23:21
    121651516    | 7-5-2011 08:23:21
    121551567    | 1-9-2010 09:25:21
    121651562    | 3-5-2017 17:23:21
我想:

   Best year | NumberOfApplications
   2016      | 21565
   Best month| NumberOfApplications
   May       | 215
我试过了

;WITH resultset AS(
        SELECT
             COUNT(CisloSmlouvy)        AS PocetSmluv
            ,DATEPART(YYYY, CAST(DatumZadosti AS DATE)) AS [Year]
            ,RN = RANK()OVER(PARTITION BY DATEPART(YYYY, CAST(DatumZadosti AS DATE)) ORDER BY DATEPART(YYYY, CAST(DatumZadosti AS DATE)))
        FROM dbo.Smlouvy
        GROUP BY
             DATEPART(YYYY, CAST(DatumZadosti AS DATE))
            ,RANK()OVER(PARTITION BY DATEPART(YYYY, CAST(DatumZadosti AS DATE)) ORDER BY DATEPART(YYYY, CAST(DatumZadosti AS DATE)))
    )   
        SELECT * FROM resultset WHERE RN = 1

任何帮助都将不胜感激。谢谢。

窗口功能应该可以帮助您:

SELECT TOP(1)
     YearCount  = COUNT(CisloSmlouvy) OVER (PARTITION BY DATEPART(YEAR, CAST(DatumZadosti AS DATE)))
    ,MonthCount = COUNT(CisloSmlouvy) OVER (PARTITION BY DATEPART(YEAR, CAST(DatumZadosti AS DATE)), DATEPART(MONTH, CAST(DatumZadosti AS DATE)))
    ,[Year]     = DATEPART(YEAR, CAST(DatumZadosti AS DATE)) 
    ,[Month]    = DATEPART(MONTH, CAST(DatumZadosti AS DATE)) 
FROM dbo.Smlouvy
ORDER BY YearCount DESC, MonthCount DESC

这并不容易,因为可能会有联系。我建议分别选择最佳年份和最佳月份,并使用
UNION ALL
将这两个结果结合起来:

select *
from
(
  (
    select top(1) with ties
      year(DatumZadosti) as y, month(DatumZadosti) as m, count(*) as cnt
    from mytable
    group by year(DatumZadosti), month(DatumZadosti)
    order by count(*) desc
  )
  union all
  (
    select top(1) with ties
      year(DatumZadosti) as y, null as m, count(*) as cnt
    from mytable
    group by year(DatumZadosti)
    order by count(*) desc
  )
) unioned
order by y desc, m desc;

请提供样本数据和预期结果。您想要一年或一个月内申请数量最多的申请吗?你的解释模棱两可。举个例子会有很大帮助。我在编辑中已经澄清了这个想法。我看到了你的结果,但这可能是什么?可以是任何一年,对吗?还是必须是最好的一年中的一个月?