如何在SQL中实现tidyr的complete()?

时间:2017-11-14 16:31:36

标签: sql r oracle tidyr complete

使用虚拟示例,我需要完成具有隐式缺失值的数据集。使用R的函数tidyrcomplete中这是微不足道的。

library(tidyr)

df <- data.frame(Borough = c('Brooklyn', 'Brooklyn', 'Queens'),
                 Crime = c('Robbery', 'Homicide', 'Drug'),
                 Count=c(1, 2, 1))

> df
   Borough    Crime Count
1 Brooklyn  Robbery     1
2 Brooklyn Homicide     2
3   Queens     Drug     1

#Complete implicit missing values

> complete(df, Borough, Crime, fill=list(Count=0))
   Borough    Crime Count
1 Brooklyn     Drug     0
2 Brooklyn Homicide     2
3 Brooklyn  Robbery     1
4   Queens     Drug     1
5   Queens Homicide     0
6   Queens  Robbery     0

但是,如果真实数据非常大并且存储在Oracle的SQL表中,那么如何使用SQL查询来完成呢?

1 个答案:

答案 0 :(得分:4)

将不同的行政区域与犯罪行交叉加入,并将原始表格连接起来,以获取0行的缺失行。

select b.borough,c.crime,coalesce(t.count,0) as count
from (select distinct borough from tbl) b
cross join (select distinct crime from tbl) c
left join tbl t on t.borough=b.borough and t.crime=c.crime