在SQL中计算多个行值

时间:2018-05-24 15:47:40

标签: sql google-bigquery

我有下表:

Pic

根据月份使用或不使用汽车的数量和年份。 A现在会编写特定年份的查询,如

> where year = 2018 (Lets pretend it now February)

我需要的结果是从2018年开始,不使用汽车。例如,对于2018年它将是3,因为从现在开始(FEB)到Dez.2017,有3个跟随0' s。如果出现1 - >停止计数。如果我对2017年感兴趣

> where year = 1.2017 

当然,无论我现在在哪个月都没关系因为2017年已经结束所以它会计数1(图片中的3个显然是错误的)

2 个答案:

答案 0 :(得分:2)

从TABLE中选择count(*) 年份< = 2018年 和sum(monthA + monthB + monthC + ...)< = 3;

答案 1 :(得分:0)

一种方法是巨型case表达式

select t.*,
       (case when greatest(jan, feb, . . . , dec) = 0 then 12
             when greatest(jan, feb, . . . , nov) = 0 then 11
             . . .
             when jan = 0 then 1
             else 0
        end) as result_i_need
from t;
相关问题