带有 over 的 Sum() 函数在 Room 数据库中不起作用 android
Sum() function with over not work in Room database android
任何人都可以帮助我下面的查询在 DB Browser 中工作正常但不适用于 Room
数据库。这是 table 和查询:
Table Transaction
:
id
amount
is_credit
查询:
SELECT *
FROM
(SELECT
id, amount,
SUM(CASE WHEN is_credit = 1 THEN amount ELSE -amount END) OVER (ORDER BY id) AS balance
FROM `Transaction`)
ORDER BY
id DESC;
我已经用 SimpleSQLiteQuery
尝试过此查询,但出现错误:
E/SQLiteLog: (1) near "(": syntax error
您正在尝试使用 SQLite Windows 函数,即 OVER Android 设备上的 SQLite 版本通常落后一些。对于 SQLite 版本 3.28.0(引入 Windows 函数时),您至少需要 API 30 (Android R)。显然,这会限制应用程序的安装基础。
你不妨看看Version of SQLite used in Android?
如果您的 SQLite 版本低于 3.25.0 then you can't use window functions,例如 SUM()
。
相反,您可以使用相关子查询来完成:
SELECT t.id,
t.amount,
(SELECT SUM(CASE WHEN tt.is_credit = 1 THEN 1 ELSE -1 END * tt.amount) FROM `Transaction` tt WHERE tt.id <= t.id) AS balance
FROM `Transaction` t
ORDER BY t.id DESC;
或自连接:
SELECT t.id,
t.amount,
SUM(CASE WHEN tt.is_credit = 1 THEN 1 ELSE -1 END * tt.amount) AS balance
FROM `Transaction` t INNER JOIN `Transaction` tt
ON tt.id <= t.id
GROUP BY t.id
ORDER BY t.id DESC;
查看简化版 demo.
任何人都可以帮助我下面的查询在 DB Browser 中工作正常但不适用于 Room
数据库。这是 table 和查询:
Table Transaction
:
id | amount | is_credit |
---|
查询:
SELECT *
FROM
(SELECT
id, amount,
SUM(CASE WHEN is_credit = 1 THEN amount ELSE -amount END) OVER (ORDER BY id) AS balance
FROM `Transaction`)
ORDER BY
id DESC;
我已经用 SimpleSQLiteQuery
尝试过此查询,但出现错误:
E/SQLiteLog: (1) near "(": syntax error
您正在尝试使用 SQLite Windows 函数,即 OVER Android 设备上的 SQLite 版本通常落后一些。对于 SQLite 版本 3.28.0(引入 Windows 函数时),您至少需要 API 30 (Android R)。显然,这会限制应用程序的安装基础。
你不妨看看Version of SQLite used in Android?
如果您的 SQLite 版本低于 3.25.0 then you can't use window functions,例如 SUM()
。
相反,您可以使用相关子查询来完成:
SELECT t.id,
t.amount,
(SELECT SUM(CASE WHEN tt.is_credit = 1 THEN 1 ELSE -1 END * tt.amount) FROM `Transaction` tt WHERE tt.id <= t.id) AS balance
FROM `Transaction` t
ORDER BY t.id DESC;
或自连接:
SELECT t.id,
t.amount,
SUM(CASE WHEN tt.is_credit = 1 THEN 1 ELSE -1 END * tt.amount) AS balance
FROM `Transaction` t INNER JOIN `Transaction` tt
ON tt.id <= t.id
GROUP BY t.id
ORDER BY t.id DESC;
查看简化版 demo.