简体   繁体   English

跨一对多关系的 DB2 SQL 计数

[英]DB2 SQL Count across one to many relationship

I have two tables in a one to many relationship within an IBM DB2 database.我在 IBM DB2 数据库中有两个表处于一对多关系。 I can't think of a way to describe what I'm doing in words easily so I'm linking an SQLFiddle.我想不出一种方法来轻松地用文字描述我在做什么,所以我正在链接一个 SQLFiddle。

Here is a working SQLFiddle on what I'm doing;这是一个关于我正在做的工作的 SQLFiddle; Click Here点击这里

The SQLFiddle works exactly like I need it to. SQLFiddle 的工作方式与我需要的完全一样。 My problem is, I am using an IBM DB2 database and the COUNT function does not seem to work.我的问题是,我使用的是 IBM DB2 数据库并且 COUNT 函数似乎不起作用。 Does anyone have a way to return what the SQLFiddle does in a IBM DB2 compatible way?有没有人有办法以 IBM DB2 兼容的方式返回 SQLFiddle 所做的事情?

Here is the error I get from i Navigator;这是我从 i Navigator 得到的错误; Click Here点击这里

You are aggregating by the wrong column.您正在按错误的列聚合。 I think this is the query you want:我认为这是您想要的查询:

SELECT Table1.quote, COUNT(Table2.quote) as TotalItem
FROM Table1 LEFT JOIN
     Table2 
     ON Table1.quote = Table2.quote
GROUP BY Table1.quote
---------^

You need to aggregate by Table1.quote because Table2.quote might be NULL , because of the LEFT JOIN .您需要按Table1.quote聚合,因为Table2.quote可能是NULL ,因为LEFT JOIN

EDIT:编辑:

Your particular problem seems to be your having two tables with the same names.您的特殊问题似乎是您有两个同名的表。 Just use column aliases:只需使用列别名:

SELECT t1.quote, COUNT(t2.quote) as TotalItem
FROM Table1 t1 LEFT JOIN
     Table2 t2
     ON t1.quote = t2.quote
GROUP BY t1.quote;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM