当多列在SQL中具有相同的ID时,加入覆盖

发布于 2025-02-13 04:47:01 字数 1878 浏览 0 评论 0原文

我剩下的是加入SQL中的另一个表格的表格,但是第二个表具有多个具有相同ID的情况,并且当我在与ID匹配时将表连接在一起时,只有最后一个带有匹配ID的情况。我希望发生的是,SQL计数与ID相匹配的次数,然后创建计数和单个情况。

表1:

ID
1AB
2SD
3OH
4SD
5作为

表2:

IDPET
1CAT
1
2
3
5
5

预期输出:

IDValCount_petscatdog catFish
21110dog
2SD1001
3OH1010
4SD0000
5AS2200

当前我的代码看起来像:

SELECT
    t1.*, t2.*
    FROM Table1 t1
    LEFT Table2 t2
    ON t1.ID = t2.ID;

ID

SDpet pet
1abdog
2sdFish
3OhDog
4dog 2 sdNa
5ASCat

如何如何我得到了这些计数列?

I am left joining a table to another table in SQL, but the second table has multiple cases with the same ID and when I join the tables together while matching with ID, only the last case with the matching ID is appended. What I would prefer to happen is that SQL count the amount of times something matches ID and then creates a count as well as the individual cases.

TABLE 1:

IDvalue
1ab
2sd
3oh
4sd
5as

TABLE 2:

IDpet
1cat
1dog
2fish
3dog
5cat
5cat

Expected Output:

IDvalcount_petscatdogfish
1ab2110
2sd1001
3oh1010
4sd0000
5as2200

Currently my code looks like:

SELECT
    t1.*, t2.*
    FROM Table1 t1
    LEFT Table2 t2
    ON t1.ID = t2.ID;

which results in

IDvaluepet
1abdog
2sdfish
3ohdog
4sdNA
5ascat

How do I get those count columns instead?

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

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

发布评论

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

评论(1

戏舞 2025-02-20 04:47:01

您正在“旋转”加入的结果。您可以使用有条件的聚合来生成这些额外的列。

例如:

select
  a.id,
  max(a.value) as val,
  count(*) as count_pets,
  sum(case when b.pet = 'cat' then 1 else 0 end) as cat,
  sum(case when b.pet = 'dog' then 1 else 0 end) as dog,
  sum(case when b.pet = 'fish' then 1 else 0 end) as fish
from table1 a
left join table2 b on b.id = a.id
group by a.id

You are "pivoting" the result of the join. You can use conditional aggregation to produce those extra columns.

For example:

select
  a.id,
  max(a.value) as val,
  count(*) as count_pets,
  sum(case when b.pet = 'cat' then 1 else 0 end) as cat,
  sum(case when b.pet = 'dog' then 1 else 0 end) as dog,
  sum(case when b.pet = 'fish' then 1 else 0 end) as fish
from table1 a
left join table2 b on b.id = a.id
group by a.id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文