我正在尝试获得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&amp; 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之和。我怎么能这样做?
修改
上述代码用于此目的。但是回到我的第二个问题。
我想要总和(sum(s1) - sum(s2))。基本上我想要波西米亚答案中所有“差异”的总和。
答案 0 :(得分: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会允许它,但会为组中列出 的每个唯一非聚合列组合返回一个随机行。
我还添加了一个列,可以根据需要计算总和的差异。
答案 1 :(得分: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)"
谢谢大家。