gpt4 book ai didi

mySQL - 根据不同列对 2 行进行分组

转载 作者:行者123 更新时间:2023-11-29 00:12:38 25 4
gpt4 key购买 nike

我正在尝试根据其他列对行进行分组。

表格是这样的:

| a_id | a_name | b_id | b_name | c_id | c_name | d_id | d_name |
|------|--------|------|--------|------|--------|------|--------|
| 1 | abcdef | 0 | | 0 | | 0 | |
| 2 | zxy | 0 | | 0 | | 0 | |
| 3 | lmao | 0 | | 0 | | 0 | |
| 0 | | 1 | oop | 0 | | 0 | |
| 0 | | 2 | abcdef | 0 | | 0 | |
| 0 | | 0 | | 1 | nope | 0 | |
| 0 | | 0 | | 2 | nothing| 0 | |
| 0 | | 0 | | 0 | | 1 | abcdef |
| 0 | | 0 | | 0 | | 2 | oop |
| 0 | | 0 | | 0 | | 3 | turtles|

我希望将所有相似的名称组合成一行。相似性由用户定义的函数 IS_SAME(str1, str2) 确定。

结果应该是这样的。

| a_id | a_name | b_id | b_name | c_id | c_name | d_id | d_name |
|------|--------|------|--------|------|--------|------|--------|
| 1 | abcdef | 2 | abcdef | 0 | | 1 | abcdef |
| 2 | zxy | 0 | | 0 | | 0 | |
| 3 | lmao | 0 | | 0 | | 0 | |
| 0 | | 1 | oop | 0 | | 2 | oop |
| 0 | | 0 | | 1 | nope | 0 | |
| 0 | | 0 | | 2 | nothing| 0 | |
| 0 | | 0 | | 0 | | 3 | turtles|

我实际上已经创建了一个查询来执行此操作,但是我在上面使用了所有费马大定理并且没有保存我使用的查询(我保存了之前用于维护此列表的 5 个查询)因为我觉得它是太简单了,没法记录。

最佳答案

这很复杂但可行。你想从一个名字列表开始,然后加入每个表并在第一列上聚合:

select max(ta.a_id) as a_id, max(ta.a_name) as a_name,
max(tb.b_id) as a_id, max(tb.b_name) as b_name,
max(tc.c_id) as a_id, max(tc.c_name) as c_name,
max(td.d_id) as a_id, max(td.d_name) as d_name
from (select a_name as name from table t union select b_name union select c_name union select d_name
) names left outer join
table ta
on is_same(ta.a_name, names.name) left outer join
table tb
on is_same(tb.b_name, names.name) left outer join
table tc
on is_same(tc.c_name, names.name) left outer join
table td
on is_same(td.d_name, names.name)
group by names.name;

关于mySQL - 根据不同列对 2 行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com