【问题标题】:SQL/R: Joining 2 tables such that the attribute values form 2nd table become attributes of the firstSQL/R:连接 2 个表,使第 2 个表的属性值成为第一个表的属性
【发布时间】:2015-02-03 05:33:54
【问题描述】:

当加入 2 个表时,我想将记录值转换为属性。 (即我有这两个表):

客户表:

|CustomerId| Name|

|1         |Abc  |

|2         |Xyz  |

我有食物偏好表:

|CustomerId|Preference |

|1         |Continental|

|1         |Italian    |

|2         |Italian    |

|2         |Indian     |

|2         |Chinese    |

现在我想将 2 个表加入下表:

|CustomerId|Name|Food-Continental|Food-Italian|Food-Indian|Food-Chinese|

|1         |Abc |TRUE            |TRUE        |FALSE      |FALSE       |

|1         |Xyz |FALSE           |TRUE        |TRUE       |TRUE        |

是否有 R 中的脚本或 SQL 查询可以帮助我轻松实现这一目标?任何帮助表示赞赏:)

【问题讨论】:

    标签: sql r join


    【解决方案1】:

    您可以使用dplyrtidyr。例如,使用此输入

    a<-read.table(text="CustomerId Name
      1 Abc
      2 Xyz", header=T)
    b<-read.table(text="CustomerId Preference
      1 Continental
      1 Italian
      2 Italian
      2 Indian
      2 Chinese", header=T)
    

    那你就可以了

    library(dplyr)
    library(tidyr)
    inner_join(a, b) %>% mutate(val=TRUE) %>% 
        spread(Preference, val, fill=FALSE)
    

    哪个产生

      CustomerId Name Chinese Continental Indian Italian
    1          1  Abc   FALSE        TRUE  FALSE    TRUE
    2          2  Xyz    TRUE       FALSE   TRUE    TRUE
    

    您可以根据需要更改列名和顺序,但这应该会为您提供数据。

    转换分两步完成。首先,我们做一个标准的合并它的数据。这会产生一个“长”格式的数据集。然后我们使用spread将长数据重新整形为宽格式。

    【讨论】:

      【解决方案2】:

      我已经得到了您使用 MSSQL 的要求。试试看。

      SELECT 
          CustomerID,
          Name,
          CASE WHEN Continental='Continental' Then 'TRUE' ELSE 'FALSE' END AS [Food-Continental],
          CASE WHEN Italian='Italian' Then 'TRUE' ELSE 'FALSE' END AS [Food-Italian],
          CASE WHEN Indian='Indian' Then 'TRUE' ELSE 'FALSE' END [Food-Indian],
          CASE WHEN Chinese='Chinese' Then 'TRUE' ELSE 'FALSE' END [Food-Chinese]
          FROM (
      SELECT 
           A.CustomerID,Name,Preference
      FROM customer A 
           LEFT JOIN 
           food B on A.CustomerID=B.CustomerID) AS C
      
           PIVOT(
                  MIN(Preference) FOR Preference IN ([Continental],[Italian],[Indian],[Chinese])
                )AS PVT
      

      【讨论】:

        猜你喜欢
        • 2019-02-22
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 2013-11-18
        • 2020-06-27
        • 1970-01-01
        相关资源
        最近更新 更多