select M.class,
( select COUNT(1)
from Ord_OrderDetail D,
Ord_OrderParent P
where
P.OrderParentID=D.OrderParentID and
D.ProductManagerID=22 and
YEAR(P.DownLoadDateForCN) =2014 and
MONTH(P.DownLoadDateForCN) = 2 AND
substring(BelongClassification,1,4) = M.class --调试发现主要是这里要用下面那个select结果class问题,BelongClass..这个是字段来的
) as saleNum
from (
--这个select 是得到分类,然后上面的where语句需要根据这里的分类得到对应的数量
select distinct substring(Productbh,1,4) as class
from Pro_Product D
where substring(Productbh,1,2)<> 'T' and
D.ProdectManagerID = 22 ) M
不知道能不能看的明白,因为表设计很多字段,没有全部弄出来,
主要是想实现查找某个时间的产品分类对应的销量,不管销量有没有,产品分类都必须列出来:订单表D如果没有某分类的销量(查不到数据情况下),他的销量为0,对应的分类也要列出来,之前遇到的问题就是没有订单情况下,分类对应的销量显示不出来0,所以改用这种方法,但查询好慢,求各位指教!
------解决方案--------------------
试试这样会不会好一些
貌似这句 substring(Productbh,1,2)<> 'T' 白写了,永远成立
[code=sql]
select M.class, s.saleNum
FROM
(
select distinct substring(Productbh,1,4) as class
from Pro_Product D
where substring(Productbh,1,2)<> 'T' and
D.ProdectManagerID = 22
) M
LEFT JOIN
( select COUNT(1) as saleNum , substring(BelongClassification,1,4) as class
from Ord_OrderDetail D,
Ord_OrderParent P
where
P.OrderParentID=D.OrderParentID and
D.ProductManagerID=22 and
P.DownLoadDateForCN>='2014-2-1' and P.DownLoadDateForCN<'2014-3-1'
) as s
ON M.class=s.class
------解决方案--------------------
SELECT Pp.calss,
COUNT(1)
FROM Ord_OrderDetail AS Od
LEFT JOIN Pro_Product AS Pp
ON Pp.ProductManageID = Od.ProductManageID
AND Od.BelongClassification LIKE Pp.class + '%'
INNER JOIN Ord_OrderParent AS Op
ON Od.OrderParentID = Op.OrderParentID
WHERE Pp.ProdectManagerID = 22
AND YEAR(Op.DownLoadDateForCN) = 2014
AND MONTH(Op.DownLoadDateForCN) = 2
GROUP BY
Pp.class
试试这样如何,然后CTRL + M看看执行计划
------解决方案--------------------
YEAR(P.DownLoadDateForCN) =2014 and
MONTH(P.DownLoadDateForCN) = 2 AND
substring(BelongClassification,1,4) = M.class
DownLoadDateForCN和BelongClassification上索引被抑制(没有索引也应该建个索引)
这些线解决掉吧
比如 DownLoadDateForCN =2014-2可以转化为大于2014-1-31 and 小于2014-03-01
BelongClassification可以使 BelongClassification like ‘M.class%’
细节自己处理
------解决方案--------------------