SQL CASE语句(多对一)

时间:2017-10-27 20:54:27

标签: sql google-bigquery case-statement

从以下多个地点的多种花卉类型表中:

Location1....Lantana
Location1....Lantana
Location1....Alba
Location1....Alba
Location2....Lantana
Location2....Gallica
Location2....Gallica
Location3....Noisette
Location3....Noisette

我想为4种不同的花类型创建4个新的(布尔)CASE语句列,如果该位置中至少有一个花有4种类型中的1种,则每列返回'1'。

实施例

如果Location1只有50个Lantanas和50个Albas

和Location2有20个Lantanas,30个Gallicas

所需的输出表

Location#  |  Total # of flowers  | # of Lantana  |  Alba  |  Gallica  |  Noisette
Location1...........100.................1...............1............0.........0
Location2...........50..................1...............0............1.........0

2 个答案:

答案 0 :(得分:1)

这是一种方法:

select location, count(*) as num_flowers,
       max(case when flow = 'Lantana' then 1 else 0 end) as Lantana,
       max(case when flow = 'Alba' then 1 else 0 end) as Alba,
       max(case when flow = 'Gallica' then 1 else 0 end) as Gallica,
       max(case when flow = 'Noisette' then 1 else 0 end) as Noisette
from t
group by location;

答案 1 :(得分:1)

不知怎的,我总是试图避免使用CASE(当然我可以的情况下),至少因为CASE语句使查询看起来很沉重而且很浓密

   

以下是CASE - 更少版本:o)

#standardSQL
SELECT location, COUNT(*) AS num_flowers,
   SIGN(COUNTIF(flower = 'Lantana')) AS Lantana,
   SIGN(COUNTIF(flower = 'Alba')) AS Alba,
   SIGN(COUNTIF(flower = 'Gallica')) AS Gallica,
   SIGN(COUNTIF(flower = 'Noisette')) AS Noisette
FROM `project.dataset.table`
GROUP BY location
-- ORDER BY location

注意:SIGN只是实际计数中的1或0(根据您的要求)。因此,如果您删除SIGN() - 哟将获得实际计数 - 这可能比仅仅0/1

更有用

您可以使用示例中的虚拟数据进行测试/播放,如下所示

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'Location1' location, 'Lantana' flower UNION ALL
  SELECT 'Location1', 'Lantana' UNION ALL
  SELECT 'Location1', 'Alba' UNION ALL
  SELECT 'Location1', 'Alba' UNION ALL
  SELECT 'Location2', 'Lantana' UNION ALL
  SELECT 'Location2', 'Gallica' UNION ALL
  SELECT 'Location2', 'Gallica' UNION ALL
  SELECT 'Location3', 'Noisette' UNION ALL
  SELECT 'Location3', 'Noisette' 
)
SELECT location, COUNT(*) AS num_flowers,
   SIGN(COUNTIF(flower = 'Lantana')) AS Lantana,
   SIGN(COUNTIF(flower = 'Alba')) AS Alba,
   SIGN(COUNTIF(flower = 'Gallica')) AS Gallica,
   SIGN(COUNTIF(flower = 'Noisette')) AS Noisette
FROM `project.dataset.table`
GROUP BY location
ORDER BY location