假设我在table_name_a
中有一些示例数据,如下所示:
code val_a date
-------------------------
1 00001 500 20191101
2 00001 1000 20191130
3 00002 200 20191101
4 00002 400 20191130
5 00003 200 20191101
6 00003 600 20191130
[20191101至20191130之间有val_a
的一些code
,我想获取每个code
上月份的最后一天的值,我的SQL查询如下:
SELECT code, max(date) AS date, val_a
FROM table_a
WHERE date BETWEEN '20090601'
AND '20090630'
GROUP BY code, val_a
但是以上查询是错误的(代码的val_a不是该月的最后一天),我的预期输出如下:
code val_a date
--------------------------
1 00001 1000 20191130
2 00002 400 20191130
3 00003 600 20191130
非常感谢您提供任何建议。
我们可以在此处尝试使用ROW_NUMBER
解决方案:
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY code ORDER BY date DESC) rn
FROM table_a
-- WHERE date BETWEEN '20090601' AND '20090630'
-- your current WHERE clause is dubious
)
SELECT code, date, val_a
FROM cte
WHERE rn = 1;