【问题标题】:SQL - check for existence of data within each day of a datasetSQL - 检查数据集每天是否存在数据
【发布时间】:2019-02-27 03:58:27
【问题描述】:

我有一个使用 Google BigQuery 的数据集,用于某个日期范围。数据是这样的:

id   date         value1   value2
--   ---------    ------   ------
1    01-feb-2019  1        2
2    01-feb-2019  2        2
3    02-feb-2019  1        2
4    02-feb-2019  2        2

我想检查每个特定日期是否存在与指定规则匹配的记录,并根据满足该规则返回该天的“状态”。因此,例如,如果那天有 value1 = 1value2 = 2 的任何记录,我的规则可能是返回当天的状态 1

上述数据的最终结果集如下所示:

date            status
----            ------
01-feb-2019     1
02-feb-2019     1

我还想检查每天的 2nd3rd 规则,如果满足这些其他规则,则返回不同的状态代码。如何在单个 SQL 查询中做到这一点(我不介意子选择等)。

【问题讨论】:

  • 请标记您正在使用的数据库。

标签: sql google-bigquery


【解决方案1】:

使用聚合:

select date,
       (case when sum(case when value1 = 1 then 1 else 0 end) > 0 and
                  sum(case when value2 = 2 then 1 else 0 end) > 0 
             then 1 else 0
        end) as status
from t
group by date;

【讨论】:

  • 稍微修正一下:第一个值为 value1,第二个值为 value2
【解决方案2】:

我使用了@Gordon Linoff 的方法。为了获得额外的规则,我使用嵌套的 case 语句。就我而言,如果不满足前两条规则,则适用第三条规则,所以我这样做:

select date,
       (case when sum(case when value1 = 1 then 1 else 0 end) > 0 and
                  sum(case when value2 = 2 then 1 else 0 end) > 0 
             then 2 -- 1st rule applies
        else
          case when sum(case when value1 = 2 then 1 else 0 end) > 0 and
                  sum(case when value2 = 2 then 1 else 0 end) > 0 
             then 1 -- 2nd rule applies
             else
                  0 -- 3rd rule applies
             end
        end) as status
from t
group by date;

【讨论】:

    【解决方案3】:

    所以我添加了规则 1,如果你想添加更多规则,只需添加更多 WHEN , THEN 等等......

    select *
    from (select date,
                 (case
                    when value1 = 1 AND value2 = 2 then 1 -- Rule1
                 -- when value1 = .. AND value2 = .. then .. -- Rule2
                 -- when value1 = ... AND value2 = ... then ... -- Rule3
                    else 0
                   end) as status
          from test
          group by date, status) as test
    where status > 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2022-10-02
      • 2012-02-13
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多