SQL/R:加入 2 个 table,使得第 2 个 table 的属性值成为第一个 table 的属性

SQL/R: Joining 2 tables such that the attribute values form 2nd table become attributes of the first

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

客户table:

|CustomerId| Name|

|1         |Abc  |

|2         |Xyz  |

并且我有食物偏好 table:

|CustomerId|Preference |

|1         |Continental|

|1         |Italian    |

|2         |Italian    |

|2         |Indian     |

|2         |Chinese    |

现在我想将 2 table 加入以下 table:

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

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

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

R 中是否有脚本或 SQL 查询可以帮助我轻松实现此目的?感谢您的帮助:)

您可以使用 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

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

改造分两步完成。首先,我们对数据进行标准合并。这会生成 "long" 格式的数据集。然后我们使用 spread 将长数据重塑为宽格式。

我使用 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