如何通过连接具有一对多关系的 3 个表来查询唯一或不同的值

How to query unique or distinct values from joining 3 tables which have one to many relationships

我想为每个类别获取不同的国家/地区值。

举个例子。

一个类别有很多公司,而这些公司又在其下有许多属于不同县的子公司。假设汽车类别及其公司是丰田和本田。我们都知道丰田和本田本身就是全球性公司,在全球设有分支机构。

我想使用字符串 aggr 显示以“|”分隔的这些国家/地区的唯一值。

我该怎么做?

示例数据:

Category table

------------------
ID   |   Name    |  
------------------
1    |  Cars     |    
2    |  Game     |
------------------
Company Table

---------------------------------------
ID   |  CompanyName    | Category
---------------------------------------
1    |  Toyota         |   Cars
2    |  Honda          |   Cars
3    |  Sony           |   Game
4    |  EA             |   Game
--------------------------------------
Branches table

--------------------------------------------------------------------
BranchID      |    BranchName     |    Country      | ParentCompany|
--------------------------------------------------------------------
1             | Toyota_America    |    USA          | Toyota       |
2             | Toyota_Japan      |    JP           | Toyota       |
3             | Honda_India_Mumbai|    IN           | Honda        |
4             | Honda_India_Delhi |    IN           | Honda        |
5             | Sony_Japan_Tokyo  |    JP           | Sony         |
6             | Sony_Japan_Hokaido|    JP           | Sony         |
7             | Sony_Spain        |    ES           | Sony         |
--------------------------------------------------------------------

对于上面的示例,我希望输出为:

---------------------------------------------
Category   |    Company       |   Contries  |
---------------------------------------------
Car        |  Toyota|Honda    |  USA | JP | IN     
Game       |   Sony |EA       |    JP | ES  

在索尼的例子中可以看到,日本虽然出现了两次,但只显示了一次。

我试过将 DISTINCT 与连接和 string_aggr 函数一起使用,但它似乎不起作用

我的查询:

SELECT DISTINCT ca.Category, co.Company, string_agg(br.Country, '|') as Countries 
FROM Category ca
LEFT JOIN Company co ON co.Category = ca.Name
LEFT JOIN Branches br ON br.ParentCompany = ca.CompanyName
Group By
ca.Category, co.Company

现在我知道使用 ID 等链接它们是最佳做法,但我只是这样做了,这样会更容易理解。

我做错了什么?

MSSQL Server 中,为了连接您可以使用 + 符号或 CONCAT 函数。因此,在您的情况下,您可以将查询更改为:

SELECT DISTINCT ca.Category, co.Company, CONCAT(br.Country, N'|') as Countries 
FROM Category ca
LEFT JOIN Company co ON co.Category = ca.Name
LEFT JOIN Branches br ON br.ParentCompany = ca.CompanyName
GROUP BY ca.Category, co.Company

您缺少 group by(),因为您正在使用聚合函数 string_agg()

SELECT ca.Category, string_agg(co.Company, '|'), string_agg(br.Country, '|') as Countries 
FROM Category ca
LEFT JOIN Company co ON co.Category = ca.Name
LEFT JOIN Branches br ON br.ParentCompany = ca.CompanyName
GROUP BY ca.Category