简体   繁体   English

SQL - 如何对案例语句进行分类?

[英]SQL - How to Categorize a Case Statement?

In this sample dataset, I have some Colors : "Red" and "Blue" and some Fruit : "Apple" and "Grapes" associated with a person/name.在这个示例数据集中,我有一些颜色:“红色”和“蓝色”以及一些水果:“苹果”和“葡萄”与人/姓名相关联。

在此处输入图像描述

My goal is to add a column for each of these groupings, called "Colors" and Fruit .我的目标是为这些分组中的每一个添加一个列,称为"Colors"Fruit These newly added columns would count +1 whenever the value is > 0 for each of their respective grouping.每当它们各自分组的值 > 0 时,这些新添加的列将计数 +1。

For example if either "Red" or "Blue" contain a value > 0, we will add +1 to Colors .例如,如果 "Red" 或 "Blue" 包含 > 0 的值,我们将 +1 添加到Colors For John Smith, since both the Red and Blue columns contain a value > 0, the Colors column will be 2. Here is the expected output:对于 John Smith,由于 Red 和 Blue 列都包含 > 0 的值,因此Colors列将为 2。这是预期的输出:

在此处输入图像描述

I know case statements can add 1 or 0, but how do we do this when we have 2 columns per grouping?我知道 case 语句可以加 1 或 0,但是当每个分组有 2 列时,我们该怎么做呢?

You do not need in CASE.你不需要在 CASE 中。

SELECT blue, red, (blue > 0) + (red > 0) colors,
       apple, grapes, (apple > 0) + (grapes > 0) fruit
FROM source_table

The values in source table shouldn't be NULL.源表中的值不应为 NULL。

SELECT
  *,
  ((CASE WHEN apple > 0 THEN 1 ELSE 0 END) + (CASE WHEN WHEN grapes > 0 THEN 1 ELSE 0 END)) as fruit,
  ((CASE WHEN red > 0 THEN 1 ELSE 0 END) + (CASE WHEN blue > 0 THEN 1ELSE 0 END)) as colors
from table

assuming the source data is in a pivoted state假设源数据处于旋转状态

with cte as (
select 'john' as name, 2 as blue, 3 as red, 2 as apple, 4 as grape union all
select 'tom', 0 , 8, 0, 0
)
select
      name
    , blue
    , red
    , coalesce((blue > 0),0) 
      + coalesce((red > 0),0)
      as colours
    , apple
    , grape
    , coalesce((apple > 0),0) 
      + coalesce((grape > 0),0)
      as fruits
from cte
name |姓名 | blue |蓝色 | red |红色 | colours |颜色 | apple |苹果| 高分辨率照片| CLIPARTO grape |葡萄| 高分辨率照片| CLIPARTO fruits水果
:--- | :--- | ---: | ---: | --: | --: | ------: | ------: | ----: | ----: | ----: | ----: | -----: -----:
john |约翰 | 2 | 2 | 3 | 3 | 2 | 2 | 2 | 2 | 4 | 4 | 2 2
tom |汤姆| 0 | 0 | 8 | 8 | 1 | 1 | 0 | 0 | 0 | 0 | 0 0

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM