-1

我正在尝试获取使用此查询的 GROUP BY 子句获得的两列总和的差异

"SELECT " + KEY_NAME + ", SUM("
            + KEY_COL1 + ") AS s1, SUM(" + KEY_COL2 + ") AS s2, "
            + KEY_ID + " FROM " + DATABASE_TABLE + " WHERE " + COUNT
            + " BETWEEN " + start + " AND " + end + " GROUP BY "
            + KEY_NAME + " HAVING (s1 - s2) < 0 ORDER BY " + KEY_NAME
            + " ASC"

我希望所有满足上述条件的字段都在我的 android 光标适配器中实现它。它没有给出任何错误,但由于某种我不知道的原因,它显示了结果的双方(其中 s1 - s2 > 0 和 s1 - s2 < 0)。基本上它给出的结果与

"SELECT " + KEY_NAME + ", SUM("
            + KEY_COL1 + ") AS s1, SUM(" + KEY_COL2 + ") AS s2, "
            + KEY_ID + " FROM " + DATABASE_TABLE + " WHERE " + KEY_COUNT
            + " BETWEEN " + start + " AND " + end + " GROUP BY "
            + KEY_NAME + " ORDER BY " + KEY_NAME
            + " ASC"

我究竟做错了什么?

此外,我想要满足上述条件的所有字段的 s1-s2 总和。我怎样才能做到这一点?

编辑:

上面的代码达到了目的。但来到我的第二个问题。

我想要总和(总和(s1)-总和(s2))。基本上我想要波西米亚答案中所有“差异”的总和。

4

2 回答 2

2

删除所有字符串构建代码噪音后,错误很明显:

SELECT
    KEY_NAME,
    SUM(KEY_COL1) AS s1,
    SUM(KEY_COL2) AS s2,
    SUM(KEY_COL1) - SUM(KEY_COL2) as diff, -- ### added this to get diff
    KEY_ID
FROM DATABASE_TABLE
WHERE COUNT BETWEEN start AND end
GROUP BY KEY_NAME, KEY_ID -- ### Added KEY_ID to group by clause
HAVING (s1 - s2) < 0
ORDER BY KEY_NAME ASC

您没有按所有非聚合列进行分组:您必须添加KEY_ID到 group by 子句。

在任何其他数据库上,这会爆炸,但 mysql 允许它,但会为 group by中列出的非聚合列的每个唯一组合返回一个随机行。

我还添加了一个列,可以根据需要计算总和的差异。

于 2013-07-08T15:22:41.600 回答
0

使用解决了

"SELECT SUM(s2) - SUM(s1) FROM ( " + "SELECT " + KEY_NAME + ", SUM("
            + KEY_COL1 + ") AS s1, SUM(" + KEY_COL2 + ") AS s2, "
            + KEY_ID + " FROM " + DATABASE_TABLE + " WHERE " + COUNT
            + " BETWEEN " + start + " AND " + end + " GROUP BY "
            + KEY_NAME + " HAVING (s1 - s2) < 0 ORDER BY " + KEY_NAME
            + " ASC)"

感谢大家。

于 2013-07-08T16:35:48.260 回答