SQL 查找重复项并获取其他值的查询
SQL query for finding duplicate and get others values
这是我的问题。我想找到重复的 'code ifls' 并获取我获得此重复代码的不同仓库
这是 table 的样子:
| code ifls | warehouse |
| 4013 | 1 |
| 4013 | 2 |
| 4013 | 3 |
| 4014 | 4 |
| 4014 | 5 |
| 4015 | 5 |
结果应如下所示:
| code ifls | warehouse | warehouse | warehouse |
| 4013 | 1 | 2 | 3 |
| 4014 | 4 | 5 | |
我尝试了那个请求但没有成功...
SELECT code ifls as ifls, (SELECT warehouse FROM catalogue WHERE code ifls= ifls)
FROM catalogue GROUP BY code ifls HAVING COUNT(code ifls) > 1
您如何在 SQL 查询中表达这一点?
您可以使用子选择和 group_concat
select `code ifls`, group_concat(warehouse)
from table
where `code ifls` in (
select `code ifls`, count(*)
from table
group by `code ifls`
having count(*) > 1
)
group by `code ifls`
这是您的代码-
SELECT `code ifls`,
SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',1) AS warehouse_1,
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 1,'',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',2),',',-1)) AS warehouse_2,
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 2,'',SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',-1)) AS warehouse_3
FROM `catalogue`
GROUP BY `code ifls`;
GROUP_CONCAT()
可能是完成您想要做的事情的最简单方法,而不会使用动态列使事情复杂化;
SELECT `code ifls`, GROUP_CONCAT(warehouse) warehouses
FROM myTable
GROUP BY `code ifls`
HAVING COUNT(*) > 1
它基本上为每个 code ilfs
提供逗号分隔的仓库列表,但 HAVING
将其限制为具有多个仓库的行。
这是我的问题。我想找到重复的 'code ifls' 并获取我获得此重复代码的不同仓库
这是 table 的样子:
| code ifls | warehouse |
| 4013 | 1 |
| 4013 | 2 |
| 4013 | 3 |
| 4014 | 4 |
| 4014 | 5 |
| 4015 | 5 |
结果应如下所示:
| code ifls | warehouse | warehouse | warehouse |
| 4013 | 1 | 2 | 3 |
| 4014 | 4 | 5 | |
我尝试了那个请求但没有成功...
SELECT code ifls as ifls, (SELECT warehouse FROM catalogue WHERE code ifls= ifls)
FROM catalogue GROUP BY code ifls HAVING COUNT(code ifls) > 1
您如何在 SQL 查询中表达这一点?
您可以使用子选择和 group_concat
select `code ifls`, group_concat(warehouse)
from table
where `code ifls` in (
select `code ifls`, count(*)
from table
group by `code ifls`
having count(*) > 1
)
group by `code ifls`
这是您的代码-
SELECT `code ifls`,
SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',1) AS warehouse_1,
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 1,'',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',2),',',-1)) AS warehouse_2,
IF((LENGTH(GROUP_CONCAT(warehouse)) - LENGTH(GROUP_CONCAT(warehouse SEPARATOR ''))) < 2,'',SUBSTRING_INDEX(GROUP_CONCAT(warehouse),',',-1)) AS warehouse_3
FROM `catalogue`
GROUP BY `code ifls`;
GROUP_CONCAT()
可能是完成您想要做的事情的最简单方法,而不会使用动态列使事情复杂化;
SELECT `code ifls`, GROUP_CONCAT(warehouse) warehouses
FROM myTable
GROUP BY `code ifls`
HAVING COUNT(*) > 1
它基本上为每个 code ilfs
提供逗号分隔的仓库列表,但 HAVING
将其限制为具有多个仓库的行。