我需要从两个不同的表中选择数据。每天的数据和计数分布,例如:
customers | sales | date
5 | 5 | 2014-11-01
0 | 2 | 2014-11-02
1 | 0 | 2014-11-03
0 | 0 | 2014-11-04
并一直持续到月底
我开始选择这种方式,但不知道如何在每天搜索并且不想在循环中进行多次搜索
SELECT (SELECT COUNT(*) FROM customers) AS customers,
(SELECT COUNT(*) FROM sales) AS sales
FROM dual
答案 0 :(得分:0)
假设每个表中都有一个日期列,您可以接近:
select date, sum(customers) as customers, sum(sales) as sales
from ((select date, count(*) as customers, 0 as sales
from customers
where date between '2014-11-01' and '2014-11-30'
group by date
) union all
(select date, 0 as customers, count(*) as sales
from sales
where date between '2014-11-01' and '2014-11-30'
group by date
)
) cs
group by date
order by date;
这将为您提供任何一个表中的所有日期。要获取所有日期,即使是那些没有数据的日期,您需要一个日期表或生成它们的方法。假设您有一个日历表,这是一种方法:
select date, sum(customers) as customers, sum(sales) as sales
from ((select date, 0 as customers, 0 as sales
from calendar
where date between '2014-11-01' and '2014-11-30'
) union all
(select date, count(*) as customers, 0 as sales
from customers
where date between '2014-11-01' and '2014-11-30'
group by date
) union all
(select date, 0 as customers, count(*) as sales
from sales
where date between '2014-11-01' and '2014-11-30'
group by date
)
) dcs
group by date
order by date;