SELECT LAST_DAY(TRUNC(date_column, 'MM')) AS last_day_of_month,
MAX(date_column) AS last_day_of_month_in_table,
SUM(value) AS total_for_entire_month,
SUM(value) KEEP (
DENSE_RANK LAST
ORDER BY TRUNC(date_column)
) AS total_for_last_day_in_table_of_month,
SUM(
CASE
WHEN TRUNC(date_column) = LAST_DAY(TRUNC(date_column))
THEN value
END
) AS total_for_only_last_day_of_month
FROM table_name
GROUP BY TRUNC(date_column, 'MM')
其中,对于样本数据:
CREATE TABLE table_name (date_column, value) AS
SELECT DATE '2023-01-01', 45 FROM DUAL UNION ALL
SELECT DATE '2023-01-02', 282 FROM DUAL UNION ALL
SELECT DATE '2023-01-31', 887 FROM DUAL UNION ALL
SELECT DATE '2023-02-01', 1 FROM DUAL UNION ALL
SELECT DATE '2023-02-20', 2 FROM DUAL;
select date, value
from
(
select
date,
value,
max(date) over (partition by trunc(date, 'mm')) as last_date
from mytable
)
where date = last_date
order by date;
或者用传统的方式:
select *
from mytable
where date in
(
select max(date)
from mytable
group by trunc(date, 'mm')
)
order by date;
4条答案
按热度按时间jtw3ybtb1#
您可以使用
LAST_DAY()
函数,该函数将返回您提供的月份的最后一天。https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions072.htm
mlnl4t2r2#
你可以使用LAST_DAY函数:
pkwftd7m3#
您可以用途:
其中,对于样本数据:
输出:
| 月最后一天|表格中的最后一天|整月总计|月表中最后一天的总计|仅上个月最后一天总计|
| --|--|--|--|--|
| 2023-01-31 00:00:00| 2023-01-31 00:00:00| 1214 | 887 | 887 |
| 2023-02-28 00:00:00| 2019 -02-20 00:00:00| 3 | 2 |* 空 *|
fiddle
dauxcl2d4#
您可以使用
MAX OVER
来获取表中一个月的最后日期。然后仅选择日期与月份的最后日期匹配的行。或者用传统的方式: