0

我想在一个月内每天从两个表中获取 SUM/Total 记录,当我在单个表上运行我的查询时,它可以工作,但是然后commulative 不工作......就像这对于第一个表是可以的。

select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, count(id) as tot_rent
from crm_rentals WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
group by date(dateadded)

这是第二张桌子,也可以。

select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, count(id) as tot_rent
from crm_sales WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
group by date(dateadded)

问题是当我想查找结果的每一天的总和时,它无法正常工作..这是我的最终查询

select dateadded,count(tot_rent) as tot_rent
from ( select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, count(id) as tot_rent
from crm_rentals WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
group by date(dateadded)
union
select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, count(id) as tot_rent
from crm_sales WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
group by date(dateadded)) s group by date(dateadded)

crm_rentals 的表结构(第一个表,日期 = Ymd)

id -----dateadded
15------2013-04-02
16------2013-04-03
17------2013-04-03

表 2 crm_sales

id------dateadded
 7------2013-04-02

结果应该是

dateadded-----tot_rent
04/02/2013 ----2
04/03/2013  ---2 //this line is not shown
4

1 回答 1

0

第一个查询给出

id -----dateadded
1------2013-04-02
2------2013-04-03

第二个查询给出

id -----dateadded
1------2013-04-02

所以工会会给

1------2013-04-02
2------2013-04-03
1------2013-04-02

它的小组会做

2------2013-04-02
1------2013-04-03

正确的方法是

15------2013-04-02
16------2013-04-03
17------2013-04-03

联盟

 7------2013-04-02

然后集团会给

2------2013-04-02
2------2013-04-03

试试这个:

select dateadded,count(tot_rent) as tot_rent
from ( select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, id as tot_rent
from crm_rentals WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
union
select DATE_FORMAT(date(dateadded),'%m/%d/%Y') as dateadded, id as tot_rent
from crm_sales WHERE YEAR(dateadded) = YEAR(CURRENT_DATE)
AND MONTH(dateadded) = MONTH(CURRENT_DATE)
) s group by dateadded
于 2013-04-11T11:55:11.847 回答