如果A列中的值为空,那么如何return列B的值,如果B也为空,那么如何移动到C的值

If null value in a Column A, then how to return the value of column B, and if also B is null, then how to move to the value of C

在 Google 大查询中有一个 table,包含日期、ID 和商店列,其目标是跟踪客户访问了多少商店:

|A_date |A_id|Store 1|B_date |B_id  |Store 2|C_date |C_id |Store 3|
--------|----|-------|-------|------|-------|-------|-----|-------|
|21.3.21|John|S1     |21.3.21|John  |S2     |21.3.21|John |S3     |
|21.3.21|Per |S1     |null   |null  |null   |null   |null |null   |
|22.3.21|Tom |S1     |null   |null  |null   |22.3.21|Tom  |S3     |
|null   |null|null   |23.3.21|Sam   |S2     |  null |null |null   |
|null   |null|null   |null   |null  |null   |24.3.21|Rob  |S3     |

我想创建一个 SQL 查询来检查第一列 (A_date) 中的日期。

我希望以这样的 table 结束,它有 dateid 列以及商店-列

Date   |ID  |Store 1|Store 2|Store 3|
21.3.21|John|S1     |S2     |S3     |
22.3.21|Tom |S1     |null   |S3     |
23.3.21|Sam |null   |S2     |null   |
24.3.21|Rob |null   |null   |S3     |

使用coalesce:

select
  coalesce(a_date, b_date, c_date) as date,
  coalesce(a_id, b_id, c_id) as id,
  store_1,
  store_2,
  store_3
from mytable

如果您有一笔交易 table 与不同的商店,那么您可以直接对该 table 使用条件聚合:

select id, date,
       logical_or(store = 'S1') as store_1,
       logical_or(store = 'S2') as store_2,
       logical_or(store = 'S3') as store_3
from t
group by id, date;

这 returns 每个商店的布尔值。但如果您需要,也可以轻松将其更改为商店名称。

您可以通过添加来计算商店的数量:

count(distinct store) as num_stores