答案 0 :(得分:2)
消除相对较重的sum(case when ...)
- 您可以使用countif
,如下例
#standardSQL
SELECT *, COUNTIF(condition) OVER(ORDER BY pos) AS groupid
FROM `yourTable`
你可以使用你的虚拟数据来玩这个,如下所示。
#standardSQL
WITH `yourTable` AS (
SELECT TRUE AS condition, 1 AS `group`, 1 AS pos UNION ALL
SELECT FALSE, 1, 2 UNION ALL
SELECT FALSE, 1, 3 UNION ALL
SELECT TRUE, 2, 4 UNION ALL
SELECT FALSE, 2, 5 UNION ALL
SELECT FALSE, 2, 6 UNION ALL
SELECT FALSE, 2, 7 UNION ALL
SELECT TRUE, 3, 8 UNION ALL
SELECT FALSE, 3, 9 UNION ALL
SELECT TRUE, 4, 10 UNION ALL
SELECT TRUE, 5, 11 UNION ALL
SELECT FALSE, 5, 12 UNION ALL
SELECT FALSE, 5, 13 UNION ALL
SELECT FALSE, 5, 14
)
SELECT *, COUNTIF(condition) OVER(ORDER BY pos) AS groupid
FROM `yourTable`
答案 1 :(得分:1)
您可以使用sum
窗口函数和case
表达式来执行此操作。
select t.*,sum(case when condition='TRUE' then 1 else 0 end) over(order by somecolumn) as groupid
from tbl t