使用 window 函数的带条件的最小日期

Min date with condition using window functions

我正在尝试使用 window 函数获取 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(date) over(partition by id order by date) 或 min()。但是,如何合并条件 ColC = t.

仍然是个问题

是否可以一行得出结果?

提前致谢!

我很想这样做:

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;

怎么样:

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

以下是针对 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