我有一个使用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
我想检查是否存在与指定规则匹配的每个特定日期的记录,并根据该规则返回该天的“状态”。因此,例如,如果当天有任何记录,其中1
和value1 = 1
value2 = 2
我对以上数据的最终结果集如下所示:
date status
---- ------
01-feb-2019 1
02-feb-2019 1
我还想每天检查一次 2nd 和 3rd 规则,如果满足这些其他规则,则返回不同的状态代码。如何在单个SQL查询中做到这一点(我不介意子选择等)。
答案 0 :(得分: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;
答案 1 :(得分:0)
所以我添加了规则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;
答案 2 :(得分:0)
我使用@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;