【问题标题】:BigQuery SQL: Counting multiples of individual products (size and color)BigQuery SQL:计算单个产品的倍数(尺寸和颜色)
【发布时间】:2019-10-11 17:18:53
【问题描述】:

我正在查看一个电子商务网站的订单表,试图确定有多少订单包含多个相同的产品,但针对不同的颜色或不同的尺寸

示例订单是包含 7 个 SKU 的订单。 1 只是 1 个产品/颜色/尺寸,但其余 6 个都是相同的产品/颜色,但 6 个不同的尺寸。那张桌子看起来像这样。

order_id | product | sizes | colors
-----------------------------------
    1    |    A    |   6   |   1
    1    |    B    |   1   |   1

如果订单在尺寸类别或颜色类别中有多个,我只想得到一个真/假。所以结果表应该是这样的。

order_id | multiple_sizes | multiple_colors
-------------------------------------------
    1    |      true      |      false 

我尝试使用IF(sizes > 1, true, false) mult_sizes, IF(colors > 1, true, false) mult_colors 之类的东西,并且可以为每一行设置为真/假,但我无法弄清楚如何仅根据 id 对其进行分组,如果 任何产品。

我过去曾使用 CASE WHEN 尝试过类似的事情,研究过使用 HAVING 以及许多其他解决方案,但我似乎无法找到解决这个确切问题的方法。抱歉,如果这已在其他地方得到解答,如果您能指出我那里,我很乐意参考其他内容。谢谢。

【问题讨论】:

  • 我觉得很奇怪orders 表的顺序会有不同大小的数量,但不是实际大小本身。不过,这似乎是您的问题所暗示的。
  • 澄清一下:这个订单表是我自己建立的。也许会有更好的解决方案可以跳过该步骤?不管怎样,我想我都准备好了。

标签: sql google-bigquery


【解决方案1】:

使用case 逻辑和聚合:

select order_id,
       (min(size) <> max(size)) as has_muliple_sizes,
       (min(color) <> max(color)) as has_muliple_colors
from t
group by order_id;

你也可以使用count(distinct):

select order_id,
       (count(distinct size) > 1) as has_muliple_sizes,
       (count(distinct color) > 1) as has_muliple_colors
from t
group by order_id;

但我认为count(distinct) 可能会产生更多开销。

编辑:

我可能误解了sizecolor 列的含义。如果这些实际上已经是 number 个尺寸和 number 个颜色,那么适当的名称将是 num_sizesnum_colors。更重要的是,SQL 只会使用max()

select order_id,
       (max(size) > 1) as has_muliple_sizes,
       (max(color) > 1) as has_muliple_colors
from t
group by order_id;

【讨论】:

  • 很抱歉再也没有回到这个问题,但您的解决方案确实有效,谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
相关资源
最近更新 更多