我正在尝试返回产品品牌名称列的每个特定事件中计数的“男性”或“女性”数量。
我尝试使用子查询并对两种性别使用相同的语法。由于我没有得到我需要的结果,我尝试在一列中计算男性的数量,然后减去总数以获得女性的数量。我使用此代码并收到消息:
语法错误:函数调用不能应用于该表达式。函数调用需要路径,例如a.b.c() 在 [8:5]
SELECT
products_brand_name,
COUNT(products_brand_name) AS total_males
FROM
`bigquery-public-data.fda_food.food_events`
WHERE
consumer_gender = "Male"
(
SELECT
COUNT((products_brand_name) - (total_males))
FROM
`bigquery-public-data.fda_food.food_events`
WHERE
consumer_gender = "Female"
)
GROUP BY
products_brand_name
LIMIT 10
如果没有一些样本数据和预期结果,还不太清楚这里的问题是什么。我想条件聚合就是你需要的:
WITH S a m p l e D a t a :
tbl AS
( Select 'A' as brand_name, 'M' as gender Union All
Select 'A', 'F' Union All
Select 'A', 'F' Union All
Select 'A', 'M' Union All
Select 'B', 'F' Union All
Select 'B', 'F' Union All
Select 'B', 'M' Union All
Select 'B', 'M' Union All
Select 'B', 'N/A' Union All
Select 'B', 'F' Union All
Select 'B', 'F'
)
-- S Q L :
Select brand_name,
Count(Case When gender = 'M' Then 1 End) as males,
Count(Case When gender = 'F' Then 1 End) as females,
Count(Case When gender IN('F', 'M') Then 1 End) as total_males_females,
Count(Case When gender NOT IN('F', 'M') Then 1 End) as total_not_male_female
From tbl
Group By brand_name
Order By brand_name
品牌名称 | 男性 | 女性 | 总_男性_女性 | 总计_非男性_女性 |
---|---|---|---|---|
A | 2 | 2 | 4 | 0 |
B | 2 | 4 | 6 | 1 |