如何在 Looker 中按日期计算状态变化?
Posted
技术标签:
【中文标题】如何在 Looker 中按日期计算状态变化?【英文标题】:How to count state changes by date in Looker? 【发布时间】:2021-01-18 09:22:14 【问题描述】:我在 BigQuery 中有一个包含创建日期和上次修改日期的任务。如果可能的话,我希望能够在同一个表中按日期报告任务打开和任务关闭事件的数量。
view: tasks
derived_table:
sql:
SELECT *
FROM UNNEST(ARRAY<STRUCT<CREATED_DATE DATE, LAST_MODIFIED DATE, ID INT64, STATE STRING>>[
('2020-12-01', '2020-12-01', 1, "OPEN"),
('2020-12-01', '2020-12-03', 2, "CLOSED"),
('2020-12-02', '2020-12-03', 3, "CLOSED"),
('2020-12-03', '2020-12-05', 4, "OPEN"),
('2020-12-05', '2020-12-05', 5, "CLOSED")])
;;
dimension_group: created
type: time
datatype: date
sql: $TABLE.created_date ;;
dimension_group: last_modified
type: time
datatype: date
sql: $TABLE.last_modified ;;
dimension: id
type: number
dimension: state
type: string
measure: number_of_tasks
type: count_distinct
sql: $id ;;
measure: number_of_open_tasks
type: count_distinct
sql: $id ;;
filters:
field: "state"
value: "OPEN"
measure: number_of_closed_tasks
type: count_distinct
sql: $id ;;
filters:
field: "state"
value: "CLOSED"
explore: tasks
我可以使用创建日期获取打开任务的数量。
我可以通过计算任务来获得关闭的任务数,其中最后修改日期在聚合期间并且状态为关闭,并带有过滤度量。
但是,如果我尝试将这些组合在一个表中,我会为每个日期组合得到一行。
如何按日期计算任务状态更改?
Date | Number of Opened Tasks | Number of Closed Tasks |
---|---|---|
2020-12-01 | 2 | 0 |
2020-12-02 | 1 | 0 |
2020-12-03 | 1 | 2 |
2020-12-04 | 0 | 0 |
2020-12-05 | 1 | 1 |
【问题讨论】:
【参考方案1】:一位同事提出了解决方案。将任务表堆叠在自身上会为每个任务创建(最多)两行。
view: tasks
derived_table:
sql:
WITH tab AS (
SELECT *
FROM UNNEST(ARRAY<STRUCT<CREATED_DATE DATE, LAST_MODIFIED DATE, ID INT64, STATE STRING>>[
('2020-12-01', '2020-12-01', 1, "OPEN"),
('2020-12-01', '2020-12-03', 2, "CLOSED"),
('2020-12-02', '2020-12-03', 3, "CLOSED"),
('2020-12-03', '2020-12-05', 4, "OPEN"),
('2020-12-05', '2020-12-05', 5, "CLOSED")])
)
SELECT *, 1 open_count, 0 closed_count, created_date AS action_date
FROM tab
UNION DISTINCT
SELECT *, 0 open_count, 1 closed_count, last_modified AS action_date
FROM tab
WHERE state = "CLOSED"
;;
dimension_group: created
type: time
datatype: date
sql: $TABLE.created_date ;;
dimension_group: last_modified
type: time
datatype: date
sql: $TABLE.last_modified ;;
dimension_group: action
type: time
datatype: date
sql: $TABLE.action_date ;;
dimension: id
type: number
dimension: state
type: string
dimension: open_count
type: number
hidden: yes
dimension: closed_count
type: number
hidden: yes
measure: number_opened
type: sum
sql: $open_count ;;
measure: number_closed
type: sum
sql: $closed_count ;;
explore: tasks
然后可以计算打开和关闭的标签。
【讨论】:
以上是关于如何在 Looker 中按日期计算状态变化?的主要内容,如果未能解决你的问题,请参考以下文章
如何计算 SQL Server 中按日期和用户分组的条目之间的平均时间?