首页 文章

SQL - 如何匹配值?

提问于
浏览
2

我在网上找到了这个练习,但不知道从哪里开始 .

给定一个包含三列(id,category,value)的表,每个id有3个或更少的可能值(价格,大小,颜色) .

现在,我如何找到两个或多个值的值彼此匹配的id?

例如:ID1(价格10,尺寸M,颜色红色),ID2(价格10,尺寸L,颜色红色),ID3(价格15,尺寸L,颜色红色)

然后输出应该是两行:ID1 ID2和ID2 ID3

1 回答

  • 0

    使用最后注释中可重复显示的数据框 DF

    library(sqldf)
    
    sqldf("select a.ID first, b.ID second
      from DF a 
      join DF b on (a.price = b.price) + 
                   (a.size = b.size) + 
                   (a.color = b.color) > 1 and
                   a.ID < b.ID")
    

    赠送:

    first second
    1     1      2
    2     2      3
    

    注意

    DF <- data.frame(ID = 1:3, 
                     price = c(10, 10, 15), 
                     size = c("M", "L", "L"),
                     color = "Red", 
                     stringsAsFactors = FALSE)
    

相关问题