【问题标题】:Refine SQL Query given list of ids优化 SQL 查询给定的 id 列表
【发布时间】: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


【解决方案1】:

您可以将前两个查询组合为:

select ids, sum( sale = 'call') as call_sales,
        sum(sale = 'person') as person_sales
from tableA
where
    ids in t.ids
group by ids
having sum(year >= 2021 and team = 'Sales') > 0;

我不确定第三个在做什么,但您可以将上面的内容用作 CTE,然后将其插入。

【讨论】:

  • 所以也将我的第一个查询用作 CTE?第三个查询是主查询,所有内容都将输入。
  • 我按照建议将前两个查询组合成一个 CTE。 CTE 中有一个子查询来获取不同的 ID。然后这个查询被内部连接到主查询上以创建主表。仍然需要大约 3 分钟才能运行,但比以前更完整。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多