我需要一些关于Android应用中的SUM功能的帮助。我有一个类似于以下内容的表:
我需要SUM
最后两个记录之间的数量Notes和最后一个记录与Note。我需要将行数31,32和33相加。它将返回90.我已经尝试了
SELECT Sum(QUANTITY) FROM fuel_table WHERE NOTE!='' ORDER BY ID DESC
但它会返回带有注释的所有数量的SUM。
答案 0 :(得分:2)
WITH max_id_with_note AS
(
SELECT MAX(ID) AS max_id
FROM YourTable
WHERE IFNULL(note, '') <> ''
)
, previous_max_id_with_note AS
(
SELECT max(ID) as max_id
FROM YourTable
WHERE IFNULL(note, '') <> ''
AND ID < (SELECT max_id FROM max_id_with_note)
)
SELECT SUM(Quantity)
FROM YourTable
WHERE (SELECT max_id FROM previous_max_id_with_note)
< ID and ID <=
(SELECT max_id FROM max_id_with_note)
答案 1 :(得分:2)
我倾向于将这个问题说成:将所有具有一个音符的行的数量相加&#34;提前&#34;他们这表明:
select sum(quantity)
from (select ft.*,
(select count(*)
from fuel_table ft2
where ft2.note = 'Yes' and ft2.id >= ft.id
) as numNotesAhead
from fuel_table ft
) ft
where numNotesAhead = 1;
答案 2 :(得分:0)
首先选择几个ROW并从此选择查询SUM()。在你的情况下它看起来像这样:
Select SUM(t1.QUANTITY) FROM (SELECT QUANTITY from fuel_table WHERE NOTE!='' ORDER BY ID limit 2) as t1
答案 3 :(得分:0)
将您的查询更改为
SELECT Sum(QUANTITY) FROM fuel_table ORDER BY ID DESC LIMIT 3
答案 4 :(得分:0)
使用sub query按QUANTITY
和ID
排除最后3行的LIMIT 3
,并将SUM()添加到结果数量中。 ..
SELECT SUM(QUANTITY) FROM (SELECT QUANTITY FROM fuel_table ORDER BY ID DESC LIMIT 3);
答案 5 :(得分:0)
我创建了一个像你一样的表并进行测试。 Andomar有个好主意,但没有犯错!
WITH max_id_with_note AS
(
SELECT MAX(ID) AS max_id
FROM fuel_table
WHERE Note <> ''
)
, previous_max_id_with_note AS
(
SELECT max(ID) as max_id
FROM fuel_table
WHERE Note <> ''
AND ID < (SELECT max_id FROM max_id_with_note)
)
SELECT SUM(Quantity)
FROM fuel_table
WHERE (SELECT max_id FROM previous_max_id_with_note)
< id and id <= (SELECT max_id FROM max_id_with_note)