Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对SQLite中最后一个(按日期)值进行分组和求和_Sql_Sqlite - Fatal编程技术网

对SQLite中最后一个(按日期)值进行分组和求和

对SQLite中最后一个(按日期)值进行分组和求和,sql,sqlite,Sql,Sqlite,例如,有一个包含数据的表: ------------------------------------------------- | date | account | currency | sum | ------------------------------------------------- | 2020-03-02 | EUR account 1 | EUR | 12000 | | 2020-03-01 | EUR account 2 | EUR

例如,有一个包含数据的表:

-------------------------------------------------
|    date    |    account    | currency |  sum  |
-------------------------------------------------
| 2020-03-02 | EUR account 1 |   EUR    | 12000 |
| 2020-03-01 | EUR account 2 |   EUR    |  3000 |
| 2020-03-06 | USD account 1 |   USD    |  1234 |
| 2020-01-02 | GBP account 1 |   GBP    |  6800 |
| 2019-11-21 | EUR account 1 |   EUR    |  3584 |
| 2019-06-15 | EUR account 1 |   EUR    | 86874 |
| 2018-02-05 | USD account 1 |   USD    | 12121 |
对数据的SQL请求必须选择最后一个值并按货币对其进行分组。结果表应具有下一个视图:

--------------------
| currency |  sum  |
--------------------
|   EUR    | 15000 |
|   USD    |  1234 |
|   GBP    |  6800 |
请建议,如何在SQLite中正确发出此请求?

您可以使用:

select t.currency, sum(t.sum)
from t
where strftime('%Y', t.date) = (select strftime('%Y', max(t2.date))
                                from t t2
                                where t2.account = t.account and t2.currency = t.currency
                               )
group by t.currency;
where
子句返回每个帐户/货币组合的最后一行(不清楚是否需要货币)。然后查询聚合这些值。

使用
行数()
窗口函数为每个
帐户选择最后一个条目,然后聚合:

select t.currency, sum(t.`sum`) `sum` 
from (
  select *, row_number() over (partition by account order by date desc) rn
  from tablename
) t 
where t.rn = 1
group by t.currency
请参阅。
结果:


同一账户在同一日期可能有多行?这不会为
EUR
提供正确的结果。您必须从日期中提取
年份
,并获取
最大值
@django unchained。非常感谢。我误读了数据,认为OP想要的是最近的日期,而不是最近的一年。
| currency | sum   |
| -------- | ----- |
| EUR      | 15000 |
| GBP      | 6800  |
| USD      | 1234  |