我有二个表,一个是保存厂家,一个是保存厂家出货记录的.
比如: 表A 有字段: id, name, 表B有字段 id,name,a_id(厂家编号).
现在我要查出每个厂家,每个月各出了多少货?要怎么优化?
结果如下
+-------------+---------+------+-----+--------+
| 厂家名称 | 1月份 | 2月 | ....| 12月份 |
+-------------+---------+------+-----+--------+
| abc | 333 | 355 |.....| 0 |
+-------------+---------+------+-----+--------+
| dec | 333 | 455 |.....| 0 |
+-------------+---------+------+-----+--------+
我现在是用二个FOR 循环,但这样如果有10个厂家以上,效率就差了.
如:
select id,name,from a
do while not .eof
for intMonth= i to 12 // 12个月,没有出货则为0
select sum(qty) as tt from b where a_id= a.id where dateDiff(year,2005-0"+intMonth+"01,b.pdate)=0 and dateDiff(month,2005-"+intMonth+"-01,b.pdate)=0
next
.moveNext
loop
这样的话,10个厂家,就要12 * 10 次了.
不晓哪个高人有好办法.谢谢.
-- 类似:
select 厂家,
[1月]=sum(case when month(日期)=1 then qty else 0 end),
[2月]=sum(case when month(日期)=2 then qty else 0 end),
[3月]=sum(case when month(日期)=3 then qty else 0 end),
....
[12月]=sum(case when month(日期)=12 then qty else 0 end)
from 表
where 日期 between 2005-1-1 and 2005-12-31
group by 厂家