第一张表:+ — + ———– +| id |国家|+ — + ———– +| 1 |印度|| 2 |澳大利亚|| 3 |加拿大|| 4 |法国|| 5 |俄罗斯|+ — + ———– +第二表:…
使用 LAG 查看上一行是否包含同一个国家/地区。
LAG
select case when lag(c.id) over (order by c.id, u.user) = c.id then null else c.id end as country_id, case when lag(c.id) over (order by c.id, u.user) = c.id then null else c.country end as country, u.user from countries c join users u on u.country_id = c.id order by c.id, u.user;
LAG 是标准的SQL,因此可用于许多DBMS(Oracle,PostgreSQL,SQL Server,MySQL版本8,......)。
如果你正在使用 SQL Server ,您可以尝试以下。
SQL Server
SELECT c.id AS country_id, c.country, t.[user] FROM (SELECT s.country_id, s.[user], Row_number() OVER ( partition BY s.country_id ORDER BY s.id) rn FROM @second s) t LEFT JOIN @country c ON t.country_id = c.id AND t.rn = 1
的 在线演示 强>
的 产量 强>
+------------+-----------+-------+ | country_id | country | user | +------------+-----------+-------+ | 1 | India | Ojas | +------------+-----------+-------+ | NULL | NULL | Raj | +------------+-----------+-------+ | NULL | NULL | Rohit | +------------+-----------+-------+ | 2 | Australia | Robin | +------------+-----------+-------+ | 3 | Canada | John | +------------+-----------+-------+ | 4 | France | Kamal | +------------+-----------+-------+ | 5 | Russia | Mary | +------------+-----------+-------+ | NULL | NULL | Bipin | +------------+-----------+-------+
的 对于其他数据库: 强>
可以不用编写相同的查询 ROW_NUMBER() 喜欢以下,以便它可以在其他数据库上工作 mysql 。
ROW_NUMBER()
mysql
SELECT c.id AS country_id, c.country, t.user FROM (SELECT s.country_id, s.user, s.id, CASE WHEN (SELECT Min(id) FROM second s2 WHERE s2.country_id = s.country_id) = s.id THEN 1 ELSE 0 END rn FROM second s) t LEFT JOIN country c ON t.country_id = c.id AND t.rn = 1 ORDER BY t.country_id ,t.id
的 MySQL db-fiddle 强>
在这里,您可以分别使用mysql和PostgreSql GROUP_CONCAT以及string_agg(some_column,',')方法的聚合方法将名称与逗号连接,并为每个国家/地区获取1条记录。
对于Mysql
SELECT countries.id AS Id, countries.name AS Country, GROUP_CONCAT(DISTINCT users.name) as Users FROM countries INNER JOIN users ON users.country_id = countries.id GROUP BY countries.id;
对于PostgreSql
SELECT countries.id AS Id, countries.name AS Country, string_agg(users.name, ',') as Users FROM countries INNER JOIN users ON users.country_id = countries.id GROUP BY countries.id;
它会产生如下结果
Id | Country | User --------------------------------- 1 | India | Ojas,Raj,Rohit 2 | Australia | Robin 3 | Canada | John 4 | France | Kamal 5 | Russia | Mary,Bipin ---------------------------------