【发布时间】:2021-09-04 13:57:19
【问题描述】:
我正在尝试改进此查询,因为它需要一段时间才能运行。困难在于数据来自一张大表,我需要汇总一些东西。首先,我需要定义我想要获取数据的 id。然后我需要汇总总销售额。然后我需要找到一些个人销售的指标。决赛桌应该是这样的:
ID | Product Type | % of Call Sales | % of In Person Sales | Avg Price | Avg Cost | Avg Discount
A | prod 1 | 50 | 25 | 10 | 7 | 1
A | prod 2 | 50 | 75 | 11 | 4 | 2
因此,每种产品和 ID 的 Call Sales 百分比加起来为 100。列总和为 100,而不是行。面对面销售的百分比也是如此。我需要单独定义 ID,因为我需要它是区域独立的。有人可以在 A 区或 B 区进行销售,但这并不重要。我们希望跨区域聚合。通过聚合子查询并使用 where 子句来获取正确的 id,它应该会减少所需的内存。
ID查询
select distinct ids from tableA as t where year>=2021 and team = 'Sales'
这应该是唯一的 id 列表
汇总电话销售和人员销售
select ids
,sum(case when sale = 'call' then 1 else 0 end) as call_sales
,sum(case when sale = 'person' then 1 else 0 end) as person_sales
from tableA
where
ids in t.ids
group by ids
使用唯一 ID 如下所示,但总销售额来自该表中的所有内容,基本上忽略了第一个查询中的 where 子句。
ids| call_sales | person_sales
A | 100 | 50
B | 60 | 80
C | 100 | 200
主表如上图
select ids
,prod_type
,cast(sum(case when sale = 'call' then 1 else 0 end)/CAST(call_sales AS DECIMAL(10, 2)) * 100 as DECIMAL(10,2)) as call_sales_percentage
,cast(sum(case when sale = 'person' then 1 else 0 end)/CAST(person_sales AS DECIMAL(10, 2)) * 100 as DECIMAL(10,2)) as person_sales_percentage
,mean(price) as price
,mean(cost) as cost
,mean(discount) as discount
from tableA as A
where
...conditions...
group by
...conditions...
【问题讨论】:
-
您需要样本数据、期望的结果以及对查询应该做什么的清晰解释。
标签: mysql sql subquery with-statement