我试图将字符串转换为SQL中的时间戳。问题非常简单,如何将此字符串转换为当天午夜开始的时间戳?
在我的数据库中,我还有一个存储在timestamp_micros
中的字段,其中一个可以工作,我认为将微控制器转换为时间戳会比字符串更容易。
例如
20170118 => timestamp
查询:
WITH allTables as (
SELECT
event.date as date,
count(*) as totalSessions,
count(DISTINCT user_dim.app_info.app_instance_id) as uniqueUsers
FROM `namehiddenonlyhere.*`
CROSS JOIN
UNNEST(event_dim) AS event
WHERE
event.name = 'session_start'
AND
event.date <= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY))
AND
event.date >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))
GROUP BY event.date
UNION ALL
SELECT
event.date as date,
count(*) as totalSessions,
count(DISTINCT user_dim.app_info.app_instance_id) as uniqueUsers
FROM `namehiddenonlyhere.*`
CROSS JOIN
UNNEST(event_dim) AS event
WHERE
event.name = 'session_start'
AND
event.date <= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY))
AND
event.date >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))
GROUP BY event.date
) SELECT 'all apps' as target, date as datapoint_time, totalSessions datapoint_value FROM allTables;
答案 0 :(得分:5)
您可以使用PARSE_DATE
或PARSE_TIMESTAMP
(格式字符串相同)来获取日期或时间戳。例如:
SELECT
d,
PARSE_DATE('%Y%m%d', d) AS date,
PARSE_TIMESTAMP('%Y%m%d', d) AS timestamp
FROM UNNEST(['20170117', '20161231']) AS d;
您可以在文档中阅读有关格式字符串的更多信息。 date和timestamp部分分别适用于PARSE_DATE
和PARSE_TIMESTAMP
。
编辑:根据您更新的问题,您可以将查询更改为以下内容:
WITH allTables as (
SELECT
event.date as date,
count(*) as totalSessions,
count(DISTINCT user_dim.app_info.app_instance_id) as uniqueUsers
FROM `namehiddenonlyhere.*`
CROSS JOIN
UNNEST(event_dim) AS event
WHERE
event.name = 'session_start'
AND
event.date <= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY))
AND
event.date >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))
GROUP BY event.date
UNION ALL
SELECT
event.date as date,
count(*) as totalSessions,
count(DISTINCT user_dim.app_info.app_instance_id) as uniqueUsers
FROM `namehiddenonlyhere.*`
CROSS JOIN
UNNEST(event_dim) AS event
WHERE
event.name = 'session_start'
AND
event.date <= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY))
AND
event.date >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY))
GROUP BY event.date
) SELECT 'all apps' as target, PARSE_DATE('%Y%m%d', date) as datapoint_time, totalSessions datapoint_value FROM allTables;
我做的唯一修改就是改变:
date AS datapoint_time
为:
PARSE_DATE('%Y%m%d', date) as datapoint_time
答案 1 :(得分:-2)
您是否尝试使用此表达式?
SELECT CONVERT(DATETIME,'20170118')