SQL-交叉点

发布于 2025-01-31 03:45:36 字数 456 浏览 3 评论 0 原文

我的表格如下:

|Group|User|
|  1  | X  | 
|  1  | Y  |
|  1  | Z  |
|  2  | X  |
|  2  | Y  |
|  2  | Z  |
|  3  | X  |
|  3  | Z  |
|  4  | X  |

我想计算组的交叉点:1& 2,1& 2& 3,1& 2& 3& 4。 然后,我想看到每个十字路口中的用户以及其中有多少个。 在给定的示例中应该是:

1&2     -> 3
1&2&3   -> 2
1&2&3&4 -> 1

是否可以使用SQL? 如果是,我该如何开始?

我每天都在与Python合作,但是现在我必须将此代码转换为SQL代码,并且对此有巨大的问题。

I have table like below:

|Group|User|
|  1  | X  | 
|  1  | Y  |
|  1  | Z  |
|  2  | X  |
|  2  | Y  |
|  2  | Z  |
|  3  | X  |
|  3  | Z  |
|  4  | X  |

I want to calculate intersections of groups: 1&2, 1&2&3, 1&2&3&4.
Then I want to see users in each intersection and how many of them are there.
In the given example should be:

1&2     -> 3
1&2&3   -> 2
1&2&3&4 -> 1

Is it possible using SQL?
If yes, how can I start?

On a daily basis I'm working with Python, but now I have to translate this code into SQL code and I have huge problem with it.

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

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

发布评论

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

评论(1

久随 2025-02-07 03:45:36

在PostgreSQL中,您可以使用 JOIN Intersect 。示例 JOIN

select count(*)
from t a
join t b on b.usr = a.usr
where a.grp = 1 and b.grp = 2

然后:

select count(*)
from t a
join t b on b.usr = a.usr
join t c on c.usr = a.usr
where a.grp = 1 and b.grp = 2 and c.grp = 3

resud

select count(*)
from t a
join t b on b.usr = a.usr
join t c on c.usr = a.usr
join t d on d.usr = a.usr
where a.grp = 1 and b.grp = 2 and c.grp = 3 and d.grp = 4

In 3 2 1 分别。

edit - 您也可以做:

select count(*)
from (
  select usr, count(*) 
  from t
  where grp in (1, 2, 3, 4)
  group by usr
  having count(*) = 4 -- number of groups
) x

请参阅

In PostgreSQL you can use JOIN or INTERSECT. Example with JOIN:

select count(*)
from t a
join t b on b.usr = a.usr
where a.grp = 1 and b.grp = 2

Then:

select count(*)
from t a
join t b on b.usr = a.usr
join t c on c.usr = a.usr
where a.grp = 1 and b.grp = 2 and c.grp = 3

And:

select count(*)
from t a
join t b on b.usr = a.usr
join t c on c.usr = a.usr
join t d on d.usr = a.usr
where a.grp = 1 and b.grp = 2 and c.grp = 3 and d.grp = 4

Result in 3, 2, and 1 respectively.

EDIT - You can also do:

select count(*)
from (
  select usr, count(*) 
  from t
  where grp in (1, 2, 3, 4)
  group by usr
  having count(*) = 4 -- number of groups
) x

See running example at db<>fiddle.

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