【问题标题】:Distinct in R while connecting to PostgreSQL using DBI Package使用 DBI 包连接到 PostgreSQL 时在 R 中有所不同
【发布时间】:2017-09-26 10:27:40
【问题描述】:

下面的代码打印:

SELECT "district_code" FROM sd_stage.table1 GROUP BY "district_code"

但我期待:

select distinct(district_code) from sd_stage.table1

代码:

library(DBI)
library(tidyverse)
library(dbplyr)

conn_obj <- DBI::dbConnect(RPostgreSQL::PostgreSQL(), 
                           host = "127.0.0.1",
                           user = "testingdb",
                           password = "admin@123")
on.exit(DBI::dbDisconnect(conn_obj))

tbl_oil_root_segment <- dplyr::tbl(conn_obj, 
       dbplyr::in_schema('sd_stage','table1'))

tbl_oil_root_segment %>% distinct(oil_district) %>% show_query()

输出正确,但生成的查询似乎不是 100%。那么无论如何我可以实现查询吗?

【问题讨论】:

    标签: r postgresql dbplyr


    【解决方案1】:
    tbl_oil_root_segment %>% select(oil_district) %>% distinct %>% show_query()
    

    将创建您期望的查询。

    但是,请注意在 SQL 中select distinct a from tselect a from t group by a 相同(请参阅this question)。

    【讨论】:

    • 我如何在您提到的上述代码中使用 order_by,以便 oil_district 处于排序状态...
    • 你可以使用来自 dplyr 的arrange
    猜你喜欢
    • 2021-03-09
    • 2019-10-25
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多