如何用SQL查询有事务的月份的最后一天?
我的数据集如下:如何用SQL查询有事务的月份的最后一天?,sql,snowflake-cloud-data-platform,snowflake-schema,Sql,Snowflake Cloud Data Platform,Snowflake Schema,我的数据集如下: +------+-------+-----+--------+ | Year | Month | Day | Amount | +------+-------+-----+--------+ | 2019 | 01 | 01 | 10 | | 2019 | 01 | 15 | 30 | | 2019 | 01 | 29 | 40 | | 2019 | 02 | 02 | 50 | | 2019 | 02 |
+------+-------+-----+--------+
| Year | Month | Day | Amount |
+------+-------+-----+--------+
| 2019 | 01 | 01 | 10 |
| 2019 | 01 | 15 | 30 |
| 2019 | 01 | 29 | 40 |
| 2019 | 02 | 02 | 50 |
| 2019 | 02 | 22 | 60 |
| 2019 | 03 | 11 | 70 |
| 2019 | 03 | 31 | 80 |
+------+-------+-----+--------+
我只想看看每个月有交易的最后一个记录日
我的首选结果如下所示:
+------+-------+--------+
| Year | Month | Amount |
+------+-------+--------+
| 2019 | 01 | 40 |
| 2019 | 02 | 60 |
| 2019 | 03 | 80 |
+------+-------+--------+
对于年和月的每个组合,您希望获得最大日和金额值:
请注意,出现在SELECT子句中但不出现在GROUP BY子句中的每一列都必须在此处使用max进行聚合
也就是说,假设数量对应于每天的总量,这就是您的示例所建议的
如果表中每天包含多个金额,则还需要对每天的金额进行汇总。我会使用类似于:
SELECT Year, Month, max(Day) as Day, max(Amount) as Amount
FROM (
SELECT Year, Month, Day, sum(Amount) as Amount
FROM t
GROUP BY Year, Month, Day
) as tmp
GROUP BY Year, Month;
在您的示例中再添加一个金额
或:
请注意,您希望在此处使用秩而不是行号,因为您需要在同一天为领带指定相同的秩标识符
当然,如果您愿意,您可以将上述任何查询包装为:
SELECT Year, Month, Amount
FROM (<query>) as q;
要删除日列。可以使用行号来实现此目的: 选择[年]、[月]、[金额] 从…起 选择按年份超额分配的行数,按日期描述的月订单* 来自表t 其中rn=1
一种方法是相关子查询:
select t.*
from t
where t.day = (select max(t2.day)
from t t2
where t2.year = t.year and t2.month = t.month
);
另一种常用方法使用行号:
按年度、月份选择年度、月份、最大日期、t组金额 您可以在下面使用: SELECT ROW_NUMBER() OVER(PARTITION BY YEAR, MONTH ORDER BY DAY DESC) as rn, * FROM yourtable QUALIFY rn = 1
使用行数函数:
with cte_order as (select year, month, amount,row_number() over(partition by month order by day desc) as identity_row from test1)
select year, month, amount, day, row_number() over(partition by month order by day desc) as identity_row from test1 qualify identity_row = 1;
从cte_订单中选择年、月、金额,其中标识行=1
使用限定函数:
with cte_order as (select year, month, amount,row_number() over(partition by month order by day desc) as identity_row from test1)
select year, month, amount, day, row_number() over(partition by month order by day desc) as identity_row from test1 qualify identity_row = 1;
尝试类似“从tablename中选择*”,其中我喜欢1个groupby Month orderby Day。用您正在使用的数据库标记您的问题。您是否尝试过选择!!!我确信它被拒绝了,因为任何聚合函数都被应用于“金额”列!不幸的是,这正是SloppyMySQL所教的。它允许将其保留为非聚合状态。任何理智的RDBMS都会拒绝它。但是这个查询不是有效的SQL还有另一个原因——即使在MySQL上也是如此。子查询需要使用别名。
select year, month, amount, day, row_number() over(partition by month order by day desc) as identity_row from test1 qualify identity_row = 1;