SQL:如何在SELECT查询结果中添加列?

发布于 2024-12-12 08:22:56 字数 185 浏览 1 评论 0原文

通常我们会在 SQL 查询中选择字段。例如

SELECT A.id FROM Member A

,但是如果我想对齐其元素对应于其他选定字段的列怎么办? 例如,我想从一个成员表中选择成员ID,并计算该成员在其他表的元组中出现的次数,

那么如何使COUNT列与选择结果对齐呢?

Usually we will select the field(s) in the SQL query. e.g.

SELECT A.id FROM Member A

But what if I want to align a column which elements correspond to the other selected field?
For example I want to select the member ID from a member table, and the COUNT that count how many times the member appear in the tuple of other table

So how do I make the COUNT column that align together with the select result?

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

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

发布评论

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

评论(3

止于盛夏 2024-12-19 08:22:56

如果我理解正确的话,这就是您想要的:

SELECT A.id, count(B.MemberID) 
FROM Member A 
LEFT JOIN TableB B on A.id = B.MemberID
group by A.id

LEFT JOIN 将包含 A 中在 B 中没有任何对应记录的记录。此外,COUNT 仅计数非-null 值,因此您需要将其与 B.MemberID 一起使用。这样,A 中与 B 中没有任何对应记录的记录计数将为 0,因为 B.MemberID 将为 NULL

If I understood you correctly, this is what you want:

SELECT A.id, count(B.MemberID) 
FROM Member A 
LEFT JOIN TableB B on A.id = B.MemberID
group by A.id

The LEFT JOIN will include records in A that do not have any corresponding records in B. Also, COUNT only counts non-null values, so you need to use it with B.MemberID. This way the count for records in A that do not have any corresponding records in B will be 0, since B.MemberID will be NULL.

从此见与不见 2024-12-19 08:22:56

我同意 @Adrian< /a> 的解决方案,但如果原始 SELECT 列表中有很多列,则它们都必须列在 GROUP BY 中。我的意思是这样的:

SELECT
   A.id,
   A.name,
   A.whatever,
   ...
   COUNT(B.member_id)
FROM Member A
  LEFT JOIN Member_Something B ON A.id = B.member_id
GROUP BY
   A.id,
   A.name,
   A.whatever,
   ...

它并不总是很方便,特别是当列实际上是表达式时。您可以采取另一种方法:

SELECT
   A.id,
   A.name,
   A.whatever,
   ...
   COALESCE(B.member_count, 0)
FROM Member A
  LEFT JOIN (
    SELECT member_id, COUNT(*) AS member_count
    FROM Member_Something
    GROUP BY member_id
  ) B ON A.id = B.member_id

I agree with @Adrian's solution, but if there were many columns in the original SELECT list, they all would have to be listed in GROUP BY. I mean something like this:

SELECT
   A.id,
   A.name,
   A.whatever,
   ...
   COUNT(B.member_id)
FROM Member A
  LEFT JOIN Member_Something B ON A.id = B.member_id
GROUP BY
   A.id,
   A.name,
   A.whatever,
   ...

It is not always convenient, especially when the columns are actually expressions. You could take another approach instead:

SELECT
   A.id,
   A.name,
   A.whatever,
   ...
   COALESCE(B.member_count, 0)
FROM Member A
  LEFT JOIN (
    SELECT member_id, COUNT(*) AS member_count
    FROM Member_Something
    GROUP BY member_id
  ) B ON A.id = B.member_id
转瞬即逝 2024-12-19 08:22:56
select member_id, count(*)
from table
group by member_id;
select member_id, count(*)
from table
group by member_id;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文