我有一张像这样的产品表
Producer Category Quality
113085 EIT 05
113085 EIT 06
113085 EIT 04
113085 EIT 05
113085 EIT 05
116159 EIT 05
116159 EIT 04
116159 EIT 04
110058 EIT 06
121570 EIT 04
我希望将每个生产者的质量等级与所有生产者的平均值之间的分配进行比较。 像这样:
Producer Category Quality Totalpercent Producerpercent
113085 EIT 05 40 60
113085 EIT 06 20 20
113085 EIT 04 40 20
我有这个选择做我想要的,但它在我的服务器上运行70-80秒,有大约260.000条记录,这很多: - )
你有什么提示可以加快这个吗?
select
Producer as Producer1,
Category as Category1,
Quality as 'Quality1',
Round(((select count(*) from base where Category=Category1 and Quality=Quality1 and deliverydate >'2016-10-01')/
(select count(*) from base where Category=Category1 and deliverydate >'2016-10-01')
*100),1) as 'Totalpercent',
Round(((select count(*) from base where Category=Category1 and Quality=Quality1 and deliverydate >'2016-10-01' and Producer=Producer1)/
((select count(*) from base where Category=Category1 and deliverydate >'2016-10-01' and Producer=Producer1))
*100),1) as 'Producerpercent'
from base where deliverydate >'2016-10-01' and Producer=113085 group by Category1, Quality1
答案 0 :(得分:0)
我认为您可以明确地简化查询。这是第一次开始:
SELECT
`Producer`,
`Category`,
`Quality`,
round(100*(SELECT COUNT(*) FROM base`subquery` WHERE subquery.Quality = mainquery.Quality) /
(SELECT COUNT(*) FROM base),1)
AS 'Totalpercent',
round((100*COUNT(*))/
(SELECT COUNT(*) FROM base WHERE `Producer`=113085),1)
AS 'Producerpercent'
FROM base `mainquery`
WHERE `Producer`=113085
GROUP BY `Category`, `Quality`
这减少了从属子查询的数量。