gpt4 book ai didi

SQL 两个表的不同计数与连接

转载 作者:行者123 更新时间:2023-12-02 17:35:13 30 4
gpt4 key购买 nike

我有两个表。

表 1 包含订单和客户代码。表 2 包含带有问题代码的订单。

我需要能够返回表 1 中客户的不同订单计数以及表 2 中问题代码为“F”的订单的不同客户计数。然后最终字段将是两者的比率。发行数量/订单数量。我正在使用 AS400/DB2 SQL。任何帮助将不胜感激。

客户 ORcnt IScnt IssueRatio
客户 1 450 37 0.082
cust2 255 12 0.047
cust3 1024 236 0.230
cust4 450 37 0.082

最佳答案

您可以对问题表使用外部联接,并使用distinct count。像这样取决于你的表定义:

select o.customercode, 
count(distinct o.orderid),
count(distinct i.orderid),
count(distinct i.orderid)/count(distinct o.orderid) ratio
from table1 o
left join table2 i on o.orderid = i.orderid and i.issuecode = 'F'
group by o.customercode

有些数据库需要将比率转换为小数——我不确定 db2。如果需要,一种方法是将结果乘以 1.0:

1.0*count(distinct i.orderid)/count(distinct o.orderid)

此外,您可能不需要 distinctcount -- 取决于您的数据...

关于SQL 两个表的不同计数与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449918/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com