SELECT语句中的条件过滤以避免连接(JOIN)。

huangapple go评论103阅读模式
英文:

Conditional filter in SELECT to avoid JOIN

问题

以下是在BigQuery中进行优化且更易读的方式来执行上述操作的SQL代码:

  1. SELECT
  2. item,
  3. SUM(cost) AS cost,
  4. IF(flag = TRUE, SUM(IF(flag = TRUE, cost, 0))) AS flag_true_cost
  5. FROM test.t1
  6. GROUP BY item;

输出结果应如下所示:

  1. item cost flag_true_cost
  2. pumpkin 3.5 3.5
  3. apple 1.4 1.4
  4. kale 20.3 2.3

这段代码将根据条件计算flag_true_cost,并且更加紧凑和易读。

英文:

I'm wondering if there's an optimized, more readable way of doing the following in BigQuery:

  1. select
  2. coalesce(a.item, b.item) as item,
  3. a.cost,
  4. b.flag_true_cost,
  5. from
  6. (
  7. select
  8. item,
  9. sum(cost) as cost,
  10. from test.t1
  11. group by item
  12. ) a
  13. full join
  14. (
  15. select
  16. item,
  17. sum(cost) as flag_true_cost
  18. from test.t1
  19. where flag = true
  20. group by item
  21. ) b
  22. on a.item = b.item;

Output:

  1. item cost flag_true_cost
  2. pumpkin 3.5 3.5
  3. apple 1.4 1.4
  4. kale 20.3 2.3

Here is some pseudo-code of what I had in mind

  1. select
  2. item,
  3. sum(cost) as cost,
  4. if(flag=true, sum(cost)) as flag_true_cost
  5. from test.t1
  6. group by item;

Here is the sample data

  1. create table test.t1 (item string, flag bool, cost numeric);
  2. insert into test.t1 values
  3. ('kale', true, 2.3),
  4. ('kale', false, 18),
  5. ('apple', true, 1.4),
  6. ('pumpkin', true, 3.5)
  7. ;

答案1

得分: 4

以下是您要翻译的内容:

> Here is some pseudo-code of what I had in mind

You are almost there. Just move the conditional within the aggregate function:

  1. select item, sum(cost) as cost,
  2. sum(if(flag=true, cost, 0)) as flag_true_cost
  3. from ayima-ad-hoc.test.t1
  4. group by item;
英文:

> Here is some pseudo-code of what I had in mind

You are almost there. Just move the conditional within the aggregate function:

  1. select item, sum(cost) as cost,
  2. sum(if(flag=true, cost, 0)) as flag_true_cost
  3. from ayima-ad-hoc.test.t1
  4. group by item;

huangapple
  • 本文由 发表于 2023年6月26日 23:23:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76558099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定