mysql 查询结果求和
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 查询结果求和相关的知识,希望对你有一定的参考价值。
SELECT i.uid,deposit+ddeposit+money as allmoney FROM pw_memberinfo i LEFT JOIN pw_members m ON m.uid=i.uid LEFT JOIN pw_memberdata d ON i.uid=d.uid sum(allmoney) where deposit+ddeposit+money>2000;
怎么求 allmoney字段结果的合
sum() 应该加在什么地方?
1、创建三张测试表,
create table pw_memberinfo(uid int, name varchar(20));
create table pw_members(companyid int, uid int);
create table pw_memberdata(uid int, deposit int, ddeposit int, money int);
2、三张表,分别插入测试数据,
insert into pw_members values(1, 1);
insert into pw_members values(1, 2);
insert into pw_members values(1, 3);
insert into pw_memberinfo values(1, 'name_1');
insert into pw_memberinfo values(2, 'name_2');
insert into pw_memberinfo values(3, 'name_3');
insert into pw_memberdata values(1,30,50,150);
insert into pw_memberdata values(2,77,50,12);
insert into pw_memberdata values(3,44,50,82);
3、查看pw_memberdata表中的记录,select * from pw_memberdata t,
4、编写sql语句,
select * from (SELECT i.uid, sum(deposit+ddeposit+money) as allmoney
FROM pw_memberinfo i
LEFT JOIN pw_members m ON m.uid=i.uid
LEFT JOIN pw_memberdata d ON i.uid=d.uid
group by i.uid
) t where allmoney>200
参考技术A SELECT i.uid,deposit+ddeposit+money as allmoney FROM------------->
SELECT i.uid,sum(deposit+ddeposit+money) as allmoney FROM
另外,因为你是多个表的左联接,考虑到有NULL记录的存在,建议你用函数ifnull处理下,避免由于NULL而造成结果有误,最终改成这样:
SELECT i.uid,sum(ifnull(deposit,0)+ifnull(ddeposit,0)+ifnull(money,0)) as allmoney
FROM pw_memberinfo i LEFT JOIN pw_members m ON m.uid=i.uid LEFT JOIN pw_memberdata d ON i.uid=d.uid
where ifnull(deposit,0)+ifnull(ddeposit,0)+ifnull(money,0)>2000;本回答被提问者采纳 参考技术B SELECT i.uid,sum(deposit+ddeposit+money) as allmoney 参考技术C 我是来顶 vinson_shen 的答案的 参考技术D 来顶顶,不懂。。嘻嘻
oracle对查询到的数据进行求和统计
对查询结果中的列中的数据进行统计求和,求和结果作为新的一行添加到查询结果的末尾,
SELECT CASE WHEN text IS NOT NULL THEN text ELSE\'合计\'END text, CASE WHEN text IS NOT NULL THEN id ELSE 0 END id, SUM(total_num)AS total_num FROM (SELECT text, (CASE WHEN ID = 1 THEN 1 WHEN ID = 2 THEN 2 WHEN ID = 3 THEN 4 WHEN ID = 4 THEN 4 WHEN ID = 5 THEN 5 WHEN ID = 6 THEN 4 WHEN ID = 7 THEN 4 END) id, SUM(total_num) total_num FROM ( SELECT aa.id, aa.text, 1 total_num FROM ( SELECT 1 id,\'AAA\' text FROM dual UNION SELECT 2 id,\'BBB\' text FROM dual UNION SELECT 3 id,\'CCC\' text FROM dual UNION SELECT 4 id,\'CCC\' text FROM dual UNION SELECT 6 id,\'CCC\' text FROM dual UNION SELECT 7 id,\'CCC\' text FROM dual UNION SELECT 5 id,\'DDD\' text FROM dual )aa ) GROUP BY text,(CASE WHEN id = 1 THEN 1 WHEN id = 2 THEN 2 WHEN id = 3 THEN 4 WHEN id = 4 THEN 4 WHEN id = 5 THEN 5 WHEN id = 6 THEN 4 WHEN id = 7 THEN 4 END ) ORDER BY id ) A GROUP BY rollup(text,id) HAVING text IS NULL OR id IS NOT NULL
查询结果中就这样多了一个统计行:
以上是关于mysql 查询结果求和的主要内容,如果未能解决你的问题,请参考以下文章