多行之间复杂的SQLite或SQL SUM()

时间:2016-02-02 19:24:05

标签: mysql sql sqlite

我需要扩展这个问题:SQLite SUM() between several rows 在表格previous table之前 和查询是:

SELECT Sum(SERVICE)
    FROM (
        SELECT ft.*, (
            SELECT count(*)
            FROM fuel_table ft2
            WHERE ft2.note='Your tank was full up.' and ft2.id>=ft.id)
        AS numNotesAhead
        FROM fuel_table ft)
    AS ft
WHERE numNotesAhead=1

但是现在我的燃料表是分开的,看起来像是:new base
我试过了:

SELECT Sum(fuel_table.SERVICE)
    FROM (
        SELECT ft.*, (
            SELECT count(*)
            FROM fuel_table ft2
            LEFT JOIN note_table ON fuel_table.EnterId = note_table.EnterId
            WHERE ft2.note='Your tank was full up.' and ft2.id>=ft.id)
        AS numNotesAhead
        FROM fuel_table ft)
    AS ft
WHERE numNotesAhead=1

但它不起作用。我的应用程序停止了。
*注意有" _"以燃料表的名义。

1 个答案:

答案 0 :(得分:1)

So there are two issues here - one is the joining of the tables, which is different from your previous problem. The second issue is doing the appropriate summation of the right values, which is already beautifully answered here: SQLite SUM() between several rows.

So, let's look at the JOIN.

Since the fuel_table has the greater number of records, we're going to expect some 'NULL' values from the desired JOIN with the note_table. (And we're not going to lose any records from fuel_table since we're joining on enterId, so we don't need a FULL OUTER JOIN). This means (for a LEFT JOIN), we want the fuel_table to be on the left:

SELECT f.id, f.service, f.enterid, n.note
FROM fuel_table f
LEFT JOIN note_table n
ON f.enterid = n.enterid

This will give us output:

id    service    enterid    note
----------------------------------
 2       50         25      Yes
 3       20         26      NULL
 4       20         35      Yes
 8       30         36      NULL
 9       15         37      NULL
10       20         42      Yes

So far, so good.

Now - rather than thinking about it - I just looked at the answer to the previous question, and substituted this subquery from the fuel_table from this answer: SQLite SUM() between several rows which is a very good answer, and I can take no credit for any part of it in the following bit ...

Putting them together you get the ugly but functional query:

SELECT SUM(fq.service) AS total
FROM
(SELECT fq2.*,
(SELECT COUNT(*)
FROM (SELECT f.id, f.service, f.enterid, n.note
     FROM fuel_table f
     LEFT JOIN note_table n
     ON f.enterid = n.enterid) fq1
WHERE fq1.note = 'Yes' AND fq1.id >= fq2.id) AS numNotesAhead
FROM 
(SELECT f.id, f.service, f.enterid, n.note
     FROM fuel_table f
     LEFT JOIN note_table n
     ON f.enterid = n.enterid) fq2) fq
WHERE numNotesAhead = 1

which returns output:

total
------
 65