1

作为标题,我想连接 SQL Server 表中的几列,我尝试使用如下paste函数但给出以下错误:

> tbl(channel,'##iris') %>% 
+   mutate(string=paste(Species,'-',
+                       Sepal.Length,'-',
+                       Sepal.Width,'-',
+                       Petal.Length,'-',
+                       Petal.Width,sep=''))
Error: PASTE() is not available in this SQL variant
4

2 回答 2

2

我在这里找到了Ben Baumer 提供的解决方案,并想在这里分享。

方法是使用CONCAT而不是paste.

> tbl(channel,'##iris') %>% 
+   group_by(Species,Sepal.Length,Sepal.Width,Petal.Length,Petal.Width) %>%
+   summarise(string=MAX(CONCAT(Species,'-',
+                               Sepal.Length,'-',
+                               Sepal.Width,'-',
+                               Petal.Length,'-',
+                               Petal.Width))) %>%
+   head(.,1)
# Source:   lazy query [?? x 6]
# Database: Microsoft SQL Server 11.00.6251[dbo@WCDCHCMSAH01\CMSAH_DC7_MP1/data_ha_amr]
# Groups:   Species, Sepal.Length, Sepal.Width, Petal.Length
  Species Sepal.Length Sepal.Width Petal.Length Petal.Width string              
  <chr>          <dbl>       <dbl>        <dbl>       <dbl> <chr>               
1 setosa          4.30        3.00         1.10       0.100 setosa-4.3-3-1.1-0.1
于 2018-01-31T07:44:14.923 回答
1

使用tidyverseon R data.framestidyr::unite将是惯用的方式。

虽然不是dplyr动词,但它还没有被翻译成通过dbplyr/使用SQL

您可以在 SQL Server 中以这种方式定义自己的unite(不幸的是我无法测试,但它应该可以工作):

unite.tbl <- function (data, col, ..., sep = "_", remove = TRUE) 
{
  dot_names <- sapply(substitute(list(...))[-1], deparse)
  shown_cols <- if (remove) 
    setdiff(data$ops$vars, dot_names)
  else data$ops$vars
  shown_col_str <- paste(shown_cols, collapse = ", ")
  concat_str <- paste0("CONCAT(",paste(dot_names, collapse = paste0(",'",sep,"',")),")")
  col <- deparse(substitute(col))
  subquery <- capture.output(show_query(data), type = "message")[-1] %>% paste(collapse = " ")
  query    <- paste("SELECT",shown_col_str,",",concat_str,"AS",col,"FROM (",subquery,")")
  tbl(data$src$con, sql(query))
}

接着 :

tbl(channel,'##iris') %>%
  unite(string,
        Species, Sepal.Length, Sepal.Width, Petal.Length, Petal.Width,
        sep = '',remove=FALSE)

对于支持||连接运算符(例如Oracle)的 DBMS,只需将concat_str定义替换为:

concat_str <- paste(dot_names, collapse = paste0(" || '", sep, "' || "))
于 2018-01-31T09:48:09.723 回答