【问题标题】:SQL two tables distinct counts with joinSQL两个表不同的计数与连接
【发布时间】:2014-12-12 18:34:05
【问题描述】:

我有两张桌子。

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

我需要能够返回表 1 中客户的不同订单计数以及表 2 中问题代码为“F”的客户的不同订单计数。那么最终字段将是两者的比率。问题计数/订单计数。我正在使用 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

【问题讨论】:

  • 如果不知道表的结构以及与您想要的结果相关的示例数据,任何人都很难为您提供帮助。此外,如果您展示您迄今为止尝试过的代码以及为什么它不起作用,人们会更愿意提供帮助。

标签: sql db2 ibm-midrange


【解决方案1】:

您可以在问题表中使用outer join,并在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 -- 取决于您的数据...

【讨论】:

  • 非常感谢先生,您让我摆脱了困境!
【解决方案2】:

如果我理解正确,这是一个 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;

【讨论】:

  • 1.9 在这里为您做什么?而且我认为你需要你的sum(...)/count(*) 来获得比率,除非我有误解。
  • 应该是1.0,用avg()比除法方便。
  • 我认为两者都是有效的解决方案。我的脚本中缺少 1.0 部分。谢谢大家!
【解决方案3】:

我正在使用一些子查询进行此操作,以使其在您提出的问题的描述方面更具可读性。 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;

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2015-09-18
    相关资源
    最近更新 更多