我有一个名为 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
我可以在代码中执行此操作,也可以使用临时表或游标在存储过程中执行此操作。
但也许有更简单的解决方案。有任何想法吗?还是更好的方法?
答案 0 :(得分:0)
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;
结果: