标签:
在使用js报表工具的时候,常常需要提供json数据进行显示,
在sql查询的时候就需要构造合适的查询结果出来;
就用到了合并两个没有关联关系的表数据,
SELECT SUM(a1.amount) AS amount, a1.date FROM ((SELECT SUM(amount) AS amount, DATE_FORMAT(time,‘%Y-%m-%d‘) AS date FROM a GROUP BY date) UNION ALL (SELECT -SUM(b.VALUE) AS s2, DATE_FORMAT(b.time,‘%Y-%m-%d‘) AS d2 FROM b GROUP BY d2)) AS a1 GROUP BY a1.date
//a表收款,b表付款,计算每天的收益(收款-付款)
//根据日期(天)分组,对两个表中的金额进行计算
//注意时间字段名称,a表相同位置的字段会覆盖b表字段名称,所以使用union要求两个表有相同的字段
//最后根据合并后时间进行分组,计算收益(计算差)
使用union 或union all
如select * from a union all select * from b 竖排合并两个表的数据
显示格式如:
a date
-204 2015-07-06
220 2015-07-15
-60 2015-07-16
220 2015-07-17
//另外一种情况,根据不同条件得到的值赋予不一样的别名(在不同的列显示)
SELECT a.date, sum(a.c1) AS s1, SUM(a.c2) AS s2 FROM( SELECT DATE_FORMAT(b.time, ‘%Y-%m-%d‘) AS date, IFNULL(( CASE b.sta WHEN 0 THEN COUNT(*) END),0 ) AS c1, IFNULL(( CASE b.sta WHEN 1 THEN COUNT(*) END),0 ) AS c2 FROM b GROUP BY b.sta,date ) AS a GROUP BY a.date
//根据类型sta=0/=1,时间分组,统计个数
得到的数据格式:
date s1 s2
2015-07-06 4 1
2015-07-08 0 1
2015-07-15 0 1
2015-07-16 1 3
标签:
原文地址:http://www.cnblogs.com/-lpf/p/4653974.html