将SUM()与LIMIT一起使用将忽略限制的表中的所有行相加

问题描述 投票:-1回答:2

以下两个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
sqlite sum limit
2个回答
1
投票

如果要应用LIMIT并在之后进行计数,则应进行嵌入式查询:

select count(*),sum(close) 
from 
(
  select close from history where symbol=494 limit 1
) t

但是此查询几乎没有道理。


0
投票

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 */

第一查询

enter image description here

第二个查询

(多个组)enter image description here

第三查询

(组中的最低和)enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.