我有两张桌子。
表1包含订单和客户代码。 表2包含带有发行代码的订单。
我需要能够从表1中返回客户的不同订单数量以及客户对发行代码为“F' F'从表2开始。然后最终的字段将是两者的比率。发行数量/订单数量。我正在使用AS400 / DB2 SQL。任何帮助将不胜感激。
Customer ORcnt IScnt IssueRatio
cust1 450 37 0.082
cust2 255 12 0.047
cust3 1024 236 0.230
cust4 450 37 0.082
答案 0 :(得分:1)
您可以在问题表中使用outer join
,在count
使用distinct
。这样的事情取决于你的表定义:
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)
此外,distinct
可能不需要count
- 取决于您的数据......
答案 1 :(得分:0)
如果我理解正确,这是一个join
查询以及条件聚合:
select t1.customer, count(*) as ordercnt,
sum(case when issuecode = 'F' then 1 else 0 end) as issuecnt,
avg(case when issuecode = 'F' then 1.0 else 0 end) as issuep
from table1 t1 join
table2 t2
on t1.orderid = t2.orderid
group by t1.customer;
答案 2 :(得分:0)
我这样做了几个子查询,使其在您提出的问题描述方面更具可读性。 sgeddes'解决方案可能也有效(并且可能表现更好),具体取决于数据的精确结构。
SELECT t.customer,
count(t.orderID_All),
count(t.orderID_F),
count(t.orderID_F)/count(t.orderID_All)
FROM
(SELECT orders.customer,
orders.orderID AS orderID_All,
issues.orderID AS orderID_F /*assuming primary/unique key is customer-orderID*/
FROM table1 orders
LEFT OUTER JOIN /*you want *all* orders on the left and just orders w/ 'F' on the right*/
(SELECT DISTINCT orderID
FROM table2
WHERE issuecode = 'F') issues ON orders.orderID = issues.orderID) t
GROUP BY t.customer;