执行非常复杂的SQL分组的有效方法:

执行非常复杂的SQL分组的有效方法:,sql,Sql,假设你有一张这样的桌子: ID | Type | Reference #1 | Reference #2 0 | 1 | [A] | {a} 1 | 2 | [B] | {b} 2 | 2 | [B] | {c} 3 | 1 | [C] | {d} 4 | 1 | [D] | {d} 5 | 1 | [E] | {d} 6 | 1 |

假设你有一张这样的桌子:

ID | Type | Reference #1 | Reference #2
0  | 1    | [A]          | {a}
1  | 2    | [B]          | {b}
2  | 2    | [B]          | {c}
3  | 1    | [C]          | {d}
4  | 1    | [D]          | {d}
5  | 1    | [E]          | {d}
6  | 1    | [C]          | {e}
有没有什么好方法可以通过“参考1”和“参考2”作为“退路”进行分组,因为没有更好的方法来表达

例如,我想将以下ID组合在一起:

{0} [Unique Reference #1], 
{1,2} [Same Reference #1],
{3,4,5,6} [{3,4,5} have same Reference #2 and {3,6} have same Reference #1]

我完全不知道该怎么做。。。有什么想法吗?

在mellamokb的查询中,分组取决于输入的顺序

产生不同的结果tahn

VALUES
    (0, 1, '[A]', '{a}'),
    (1, 2, '[B]', '{b}'),
    (2, 2, '[B]', '{c}'),
    (3, 1, '[C]', '{e}'), //group 3
    (4, 1, '[D]', '{d}'), // group 4
    (5, 1, '[E]', '{d}'), // group 4
    (6, 1, '[C]', '{d}'); // group 3
如果您可以指定引用的自然顺序,那么这可能是有意的,但是如果它们不是,那就是一个问题。“解决”这个问题或指定另一个问题的方法是,所有相等的引用1创建一组元素,这些元素的成员是它们自己,而那些元素的引用2至少等于该集合的一个成员

在SQL中:

with groupings as (
  select
    ID,Reference1,Reference2,
    (select min(ID) from Table1 t2
     where t2.Reference1=t1.Reference1 or t2.Reference2=t1.Reference2 ) as minID
  from
    Table1 t1
)
select
    t1.ID,t1.Reference1,t1.Reference2,t1.minid as round1,
    (select min(t2.minid) from
            groupings t2
      INNER JOIN groupings t3 ON t1.Reference2=t2.Reference2
) as minID
  from
    groupings t1

每次都应该生成完整的分组。

您是否建议引用1的计数是按顺序排列的?我不知道具体怎么做,但我认为您需要将两个独立的select语句外部连接在一起,以实现所需的功能…测试模式:如何“[Z]”,“{e}”'在此示例中是否分组?我认为此问题需要分层查询答案。我已删除我的答案,因为它部分不正确,这是一个更好的答案。
with groupings as (
  select
    ID,Reference1,Reference2,
    (select min(ID) from Table1 t2
     where t2.Reference1=t1.Reference1 or t2.Reference2=t1.Reference2 ) as minID
  from
    Table1 t1
)
select
    t1.ID,t1.Reference1,t1.Reference2,t1.minid as round1,
    (select min(t2.minid) from
            groupings t2
      INNER JOIN groupings t3 ON t1.Reference2=t2.Reference2
) as minID
  from
    groupings t1