使用窗口函数的条件最小日期

时间:2017-06-20 11:31:19

标签: sql google-bigquery window-functions

我正在尝试使用窗口函数来获取ColC变为True的第一个日期(按ID分组)并创建一个新列。

id         date           ColC
1        2017-04-20        t
1        2017-04-19        t
1        2017-04-18        t
2        2017-04-20        t
2        2017-04-19        f

因此,我希望得到以下结果:

id       first_date           
1        2017-04-18 
2        2017-04-20   

到目前为止,我已经知道使用FIRST_VALUE(日期)(按ID排序按日期分区)或min()。但是,如何结合条件ColC = t

仍然是一个问题

是否可以用一行获得结果?

提前谢谢!

3 个答案:

答案 0 :(得分:1)

我很想做:

select min(case when colc = 't' then date end) over (partition by id)

当然,对于您的特定结果,group by更简单:

select id, min(date)
from t
where colc = 't'
group by id;

答案 1 :(得分:1)

下面是BigQuery Standard SQL并处理更多通用案例,当ColC可以将其状态从f更改为t并返回f然后再次返回t多次

  
#standardSQL
WITH yourTable AS (
  SELECT 1 AS id, DATE '2017-04-20' AS date, 't' AS ColC UNION ALL
  SELECT 1, DATE '2017-04-19', 't' UNION ALL
  SELECT 1, DATE '2017-04-18', 't' UNION ALL
  SELECT 2, DATE '2017-04-21', 't' UNION ALL
  SELECT 2, DATE '2017-04-20', 't' UNION ALL
  SELECT 2, DATE '2017-04-19', 'f' UNION ALL
  SELECT 2, DATE '2017-04-18', 't' UNION ALL
  SELECT 2, DATE '2017-04-17', 'f' 
)
SELECT id, date AS switch_date
FROM (
  SELECT 
    id, date, ColC, 
    LAG(ColC) OVER(PARTITION BY id ORDER BY date) AS prevColC
  FROM yourTable
)
WHERE ColC = 't' AND IFNULL(prevColC, 'f') != 't'
-- ORDER BY id, date DESC 

答案 2 :(得分:0)

怎么样:

select id, min(date) as first_date from tablename where ColC='t' group by id