如何统计同一个表中名字之间的关系?

发布于 2024-12-26 17:18:56 字数 528 浏览 1 评论 0原文

我有一个名为 names 的表,其中的行由名称和该名称的组组成。

我想计算任何两个名字在任何组中一起出现的次数。

表格

name    | group
--------+------
Renato  |   1
John    |   1 
Paul    |   1
Renato  |   2
John    |   2
John    |   3
Paul    |   3 

预期结果

name 1  | name 2 |count
--------+--------+-----
Renato  | John   |  2
Renato  | Paul   |  1
John    | Renato |  2 
John    | Paul   |  2
Paul    | Renato |  1
Paul    | John   |  2

我该如何做到这一点?

I have a table called names with rows consisting of a name and a group for that name.

I want to count how much times any two names appear together in any group.

Table

name    | group
--------+------
Renato  |   1
John    |   1 
Paul    |   1
Renato  |   2
John    |   2
John    |   3
Paul    |   3 

Expected result

name 1  | name 2 |count
--------+--------+-----
Renato  | John   |  2
Renato  | Paul   |  1
John    | Renato |  2 
John    | Paul   |  2
Paul    | Renato |  1
Paul    | John   |  2

How I can do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌伤ぢ 2025-01-02 17:18:56
SELECT n1.name AS "name 1", n2.name AS "name 2",
    COUNT(*) AS "count"
FROM "names" AS n1
JOIN "names" AS n2
    ON n1.group = n2.group
WHERE n1.name <> n2.name
GROUP BY n1.name, n2.name
SELECT n1.name AS "name 1", n2.name AS "name 2",
    COUNT(*) AS "count"
FROM "names" AS n1
JOIN "names" AS n2
    ON n1.group = n2.group
WHERE n1.name <> n2.name
GROUP BY n1.name, n2.name
绝不放开 2025-01-02 17:18:56
SELECT 
  lefttbl.name as name_1,
  righttbl.name as name_2,
  count(*) as together_count
FROM
  xx AS lefttbl
  INNER JOIN xx AS righttbl on lefttbl.group=righttbl.group
WHERE lefttbl.name<>righttbl.name
GROUP BY name_1,name_2
;

为您提供所需的结构。我更新了 SQL,删除了对引号的需要,以满足那些能够正确识别引用不兼容但不愿意纠正它的人的需求。

SELECT 
  lefttbl.name as name_1,
  righttbl.name as name_2,
  count(*) as together_count
FROM
  xx AS lefttbl
  INNER JOIN xx AS righttbl on lefttbl.group=righttbl.group
WHERE lefttbl.name<>righttbl.name
GROUP BY name_1,name_2
;

Gives you the desired structure. I updated the SQL to remove the need for quotes, as to satisfy those, who are able to correctly identify a quoting incompatibility, but unwilling to correct it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文