SQL:如何在SELECT查询结果中添加列?
通常我们会在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,这就是您想要的:
LEFT JOIN
将包含 A 中在 B 中没有任何对应记录的记录。此外,COUNT
仅计数非-null 值,因此您需要将其与B.MemberID
一起使用。这样,A 中与 B 中没有任何对应记录的记录计数将为 0,因为B.MemberID
将为NULL
。If I understood you correctly, this is what you want:
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 withB.MemberID
. This way the count for records in A that do not have any corresponding records in B will be 0, sinceB.MemberID
will beNULL
.我同意 @Adrian< /a> 的解决方案,但如果原始 SELECT 列表中有很多列,则它们都必须列在 GROUP BY 中。我的意思是这样的:
它并不总是很方便,特别是当列实际上是表达式时。您可以采取另一种方法:
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:
It is not always convenient, especially when the columns are actually expressions. You could take another approach instead: