想到的第一个方法是将日期转换为文本,因为已经有针对不同形式的文本操作的 dbplyr 翻译。这种方法依赖于as.character 将日期转换为字符,并依赖substr 将年、月或日提取为文本。然后可以将其转换为数字并进一步操作。
(1) 设置模拟数据库连接以测试翻译(选择您喜欢的 SQL 风格):
library(dplyr)
library(dbplyr)
df = data.frame(start_dates = c('2020-01-31', '2020-02-28', '2020-03-31'))
# simulate a connection to test translation (pick your preferred flavor)
df = tbl_lazy(df, con = simulate_mssql())
# df = tbl_lazy(df, con = simulate_hive())
# df = tbl_lazy(df, con = simulate_impala())
# df = tbl_lazy(df, con = simulate_oracle())
# df = tbl_lazy(df, con = simulate_postgres())
# df = tbl_lazy(df, con = simulate_mysql())
# df = tbl_lazy(df, con = simulate_sqlite())
(2) 示例——提取日期分量,递增年份,重新组合:
output = df %>%
mutate(text_date = as.character(start_dates)) %>%
mutate(text_year = substr(text_date, 1, 4),
text_month = substr(text_date, 6, 7),
text_day = substr(text_date, 9, 10)) %>%
mutate(num_year = as.numeric(text_year),
num_month = as.numeric(text_month),
num_day = as.numeric(text_day)) %>%
select(start_dates, num_year, num_month, num_day) %>%
mutate(next_year = num_year + 1) %>%
mutate(next_year_text_date = paste0(next_year, '-', num_month, '-', num_day)) %>%
mutate(next_year_date = as.Date(next_year_text_date)) %>%
select(start_dates, next_year_date)
调用show_query(output) 然后给出以下翻译,但格式不那么好。我知道嵌套查询不被认为是良好的 SQL 做法,但这就是 dbplyr 翻译的工作原理。
SELECT `start_dates`
, TRY_CAST(`next_year_text_date` AS DATE) AS `next_year_date`
FROM (
SELECT `start_dates`
, `num_year`
, `num_month`
, `num_day`
, `next_year`
, `next_year` + '-' + `num_month` + '-' + `num_day` AS `next_year_text_date`
FROM (
SELECT `start_dates`
, `num_year`
, `num_month`
, `num_day`
, `num_year` + 1.0 AS `next_year`
FROM (
SELECT `start_dates`
, TRY_CAST(`text_year` AS FLOAT) AS `num_year`
, TRY_CAST(`text_month` AS FLOAT) AS `num_month`
, TRY_CAST(`text_day` AS FLOAT) AS `num_day`
FROM (
SELECT `start_dates`
, `text_date`
, SUBSTRING(`text_date`, 1, 4) AS `text_year`
, SUBSTRING(`text_date`, 6, 2) AS `text_month`
, SUBSTRING(`text_date`, 9, 2) AS `text_day`
FROM (
SELECT `start_dates`
, TRY_CAST(`start_dates` AS VARCHAR(MAX)) AS `text_date`
FROM `df`
) `q01`
) `q02`
) `q03`
) `q04`
) `q05`
(3) 提取组件,压缩:
output = df %>%
mutate(num_year = as.numeric(substr(as.character(start_dates), 1, 4)),
num_month = as.numeric(substr(as.character(start_dates), 6, 7)),
num_day = as.numeric(substr(as.character(start_dates), 9, 10)))
使用show_query(output) 的 SQL 翻译要短得多:
SELECT `start_dates`
, TRY_CAST(SUBSTRING(TRY_CAST(`start_dates` AS VARCHAR(MAX)), 1, 4) AS FLOAT) AS `num_year`
, TRY_CAST(SUBSTRING(TRY_CAST(`start_dates` AS VARCHAR(MAX)), 6, 2) AS FLOAT) AS `num_month`
, TRY_CAST(SUBSTRING(TRY_CAST(`start_dates` AS VARCHAR(MAX)), 9, 2) AS FLOAT) AS `num_day`
FROM `df`
希望这适用于 dbplyr 可以转换的所有 SQL 风格。由于我无法访问每种 SQL 风格来对其进行测试,因此来自在特定 SQL 风格上测试过它的人的 cmets 会很有帮助。