以下两个SQLite查询返回相同的结果,LIMIT被忽略。有解决方法吗?
SQL
select count(*),sum(close) from history where symbol=494 limit 1;
select count(*),sum(close) from history where symbol=494;
输出
# Count(*) Sum(close)
1. 501 97836.04
2. 501 97836.04
如果要应用LIMIT并在之后进行计数,则应进行嵌入式查询:
select count(*),sum(close)
from
(
select close from history where symbol=494 limit 1
) t
但是此查询几乎没有道理。
count()和sum()是aggregate函数,它们作用于行的[[GROUP,返回每个组的单个值(行)。如果没有GROUP BY子句如果存在,则默认组为ALL行。
因此在这种情况下使用LIMIT没有意义例如,如果您的历史记录表具有日期列,并且您根据日期进行了分组,那么如果存在多个组,则可以得到多行,并且LIMIT可能会很有意义。
考虑以下示例SQL和结果:-
DROP TABLE IF EXISTS history;
CREATE TABLE IF NOT EXISTS history (symbol INTEGER,close REAL, date TEXT);
INSERT INTO history VALUES
(494,2103.04,'20019-01-01'),(494,512.45,'2019-02-01'),(494,765.34,'2019-03-01'),
(494,2103.04,'20019-01-02'),(494,512.45,'2019-02-02'),(494,765.34,'2019-03-02'),
(495,2103.04,'20019-01-01'),(495,512.45,'2019-02-01'),(495,765.34,'2019-03-01')
;
/* Excluded by selects due to WHERE symbol=494 */
select count(*),sum(close) from history where symbol=494;
/* multiple counts and sums due to grouping by year and month */
select count(*),sum(close) from history where symbol=494 GROUP BY strftime('%Y%m',date);
/* IN this case LIMIT in association with ORDER returns the lowest sum of all the groups (year and month) */
select count(*),sum(close) from history as h where symbol=494 GROUP BY strftime('%Y%m',date) ORDER BY sum(close) ASC LIMIT 1;
DROP TABLE IF EXISTS history; /* cleanup test */
第一查询
第二个查询
(多个组)第三查询
(组中的最低和)