Tsql 使用group by获得唯一月份

Tsql 使用group by获得唯一月份,tsql,group-by,sql-server-2016,Tsql,Group By,Sql Server 2016,我有一个名为tbl_points的表,其中包含以下列: [key] identity [fkey] int -> forign key from other table [points] int -> number [inputdate] datetime -> getdate() 价值观包括: key,fkey,points,inputdate 1,23,5,20170731 2,23,2,20170801 3,23,4,20170801 4,25,2,20170801

我有一个名为tbl_points的表,其中包含以下列:

[key] identity
[fkey] int -> forign key from other table
[points] int -> number
[inputdate] datetime -> getdate()
价值观包括:

key,fkey,points,inputdate

1,23,5,20170731
2,23,2,20170801
3,23,4,20170801
4,25,2,20170801
5,25,2,20170802
6,23,5,20170803
7,25,3,20170803
8,23,5,20170804
我正在执行如下查询:

select fkey,sum(points) points,month(inputdate) mnd,year(inputdate) yy
from tbl_points 
group by fkey,month(inputdate) mnd,year(inputdate)
order by year(inputdate),month(inputdate) mnd,points
其结果是:

fkey,points,mnd,yy

23,14,8,2017
25,7,8,2017
25,5,7,2017

到目前为止还不错。现在我只想要每个月的前1名,所以

23,14,8,2017
25,5,7,2017
我可以在代码中,或者在带有临时表或游标的存储过程中这样做

但也许有更简单的解决办法。有什么想法吗?还是更好的方法

DECLARE @tbl_points TABLE
    (
      [key] INT ,
      [fkey] INT ,
      [points] INT ,
      [inputdate] DATETIME
    );

INSERT  INTO @tbl_points
VALUES  ( 1, 23, 5, '2017-07-31' ),
        ( 2, 23, 2, '2017-08-01' ),
        ( 3, 23, 4, '2017-08-01' ),
        ( 4, 25, 2, '2017-08-01' ),
        ( 5, 25, 2, '2017-08-02' ),
        ( 6, 23, 5, '2017-08-03' ),
        ( 7, 25, 3, '2017-08-03' ),
        ( 8, 23, 5, '2017-08-04' ); 


/* Your query */
SELECT  fkey ,
        SUM(points) points ,
        YEAR(inputdate) [year] ,
        MONTH(inputdate) [month]
FROM    @tbl_points
GROUP BY fkey ,
        MONTH(inputdate) ,
        YEAR(inputdate)
ORDER BY YEAR(inputdate) ,
        MONTH(inputdate) ,
        points;


/* Query you want */
SELECT  s.fkey ,
        s.points ,
        s.[year] ,
        s.[month]
FROM    ( SELECT    fkey ,
                    SUM(points) points ,
                    YEAR(inputdate) [year] ,
                    MONTH(inputdate) [month] ,
                    ROW_NUMBER() OVER ( PARTITION BY MONTH(inputdate) ORDER BY YEAR(inputdate) , MONTH(inputdate) , SUM(points) ASC ) [Row]
          FROM      @tbl_points
          GROUP BY  fkey ,
                    MONTH(inputdate) ,
                    YEAR(inputdate)
        ) AS s
WHERE   s.Row = 1;
结果:

结果:


是否链接页面帮助右侧的相关问题?可能使用排名函数ROW_NUMBER(),然后使用WHERE子句仅返回值为1的行。是否链接页面帮助右侧的相关问题?可能使用排名函数ROW_NUMBER())然后使用WHERE子句仅返回值为1的行。也许您还可以解释键的差异,以便OP了解代码工作的原因。您所说的键差异是指字段“fkey”?在本例中,fkey与另一个表(tbl_stories)相关,其中它是标识。人们可以给故事打分,每个月都会有一个故事在上面。也许你也可以解释关键区别,让OP知道你的代码为什么工作。你说的关键区别是“fkey”字段?在本例中,fkey与另一个表(tbl_stories)相关,其中它是标识。人们可以给故事打分,每个月都会有一个故事在上面。