如何在没有分组的情况下获得结果?
我的表
id user_id amount currency_id type status
5 2 2.00 1 0 0
6 3 3.00 1 0 0
4 1 1.00 1 0 0
7 4 4.00 1 0 0
8 5 3.00 1 1 0
我执行以下选择
SELECT id, user_id, amount, currency_id, SUM( amount )
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
结果:
id user_id amount currency_id SUM( amount )
5 2 2.00 1 6.00
如何得到这个结果:
id user_id amount currency_id SUM( amount )
5 2 2.00 1 0 6.00
6 3 3.00 1 0 6.00
4 1 1.00 1 0 6.00
答案 0 :(得分:1)
你可以加入
SELECT id,
user_id,
amount,
currency_id,
a.totalAmount
FROM market
CROSS JOIN
(
SELECT SUM(amount) totalAmount
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
) a
WHERE amount <=3
AND type = 0
AND status = 0
或使用内联子查询,
SELECT id,
user_id,
amount,
currency_id,
(
SELECT SUM(amount) totalAmount
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
) totalAmount
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
答案 1 :(得分:1)
如果您的目的是返回符合此条件的单个记录并总结它们,并且您实际上并不需要将SUM值作为每行的字段(不确定为什么会这样),那么我建议您在GROUP BY ... WITH ROLLUP
修饰符处。它的工作原理如下:
SELECT id, user_id, SUM(amount) AS `amounts`, currency_id
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
GROUP BY id WITH ROLLUP
这里我按id
进行分组,因为这会使各个记录保持不变,因为此值是唯一的
您的输出将如下所示:
id user_id amounts currency_id
5 2 2.00 1
6 3 3.00 1
4 1 1.00 1
NULL 3 6.00 1
请注意,最后一条记录提供了SUM()
功能的汇总。另请注意,汇总行中user_id
和currency_id
的值是不确定的,因为它们不是GROUP BY或聚合的一部分。因此,它们毫无意义。
答案 2 :(得分:0)
你走了:
SELECT id, user_id, amount, currency_id, t2.total
FROM market, (
SELECT SUM(amount) AS total
FROM market
WHERE amount <=3
AND type = 0
AND status = 0
) AS t2
WHERE amount <=3
AND type = 0
AND status = 0