等效于excel COUNTIFS

时间:2019-07-27 17:59:13

标签: sql google-bigquery

我正在尝试从excel类型的结果中获取一个COUNTIFS

这是产品表:

命名产品

john    car
john    football
john    image
max     food
max     tv
max     laptop
max     image
max     image
max     image
alex    tv
alex    laptop
alex    image
alex    cake
alex    cake
alex    cake
alex    cake
alex    car

输出应为:

名称产品人均产品数量相同类型的产品数量

john    car     1   2
john    football1   1
john    image   1   5
max     food    1   1
max     tv      1   2
max     laptop  1   2
max     image   3   5
alex    tv      1   2
alex    laptop  1   2
alex    image   1   5
alex    cake    4   4
alex    car     1   2

每人的产品数是按产品名称分类的产品计数 和相同类型的产品数是基于每个产品的总计数

例如,图像重复了3次,因此最大值为C,答案是C,答案是3,但表中有5次,所以答案是D,答案是5。

我尝试但未获得正确答案:

SELECT
  name,
  product,
  COUNT(*),
  COUNT(*) OVER (PARTITION BY product),
from products
GROUP BY 1,2
ORDER BY 1

3 个答案:

答案 0 :(得分:1)

使用名称和产品分组

  SELECT  name,
      product,    
      COUNT(*),    
      COUNT(*) OVER (partition by product)

    from products

    GROUP BY name,product

    ORDER BY 1

答案 1 :(得分:1)

#standardSQL
SELECT name, product, product_per_person,
  SUM(product_per_person) OVER(PARTITION BY product) product_total
FROM (
  SELECT
    name,
    product,
    COUNT(*) product_per_person
  FROM `project.dataset.products`
  GROUP BY 1,2
)
ORDER BY 1 

如果要应用于示例数据-结果应为

Row name    product     product_per_person  product_total    
1   alex    cake        4                   4    
2   alex    car         1                   2    
3   alex    image       1                   5    
4   alex    laptop      1                   2    
5   alex    tv          1                   2    
6   john    car         1                   2    
7   john    football    1                   1    
8   john    image       1                   5    
9   max     food        1                   1    
10  max     image       3                   5    
11  max     laptop      1                   2    
12  max     tv          1                   2    

答案 2 :(得分:0)

您非常亲密。您需要求和 COUNT(*)。您可以直接在聚合查询中执行此操作:

SELECT name, product,
       COUNT(*),
       SUM(COUNT(*)) OVER (PARTITION BY product)
FROM products
GROUP BY 1, 2
ORDER BY 1