试图一起添加两个查询

时间:2016-02-25 12:51:35

标签: sql informix

我试图再添加一列作为剩余行数的列,
 我不想要包含我的计划数量与完成数量匹配的行 (plan_qty!= cmp_qty)

SELECT   od_f.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value
FROM     od_f,
         om_f
WHERE    od_f.ob_oid = om_f.ob_oid
GROUP BY od_f.ob_oid, total_value
ORDER BY Percent_Cmp desc

这是一个返回我想要的新列的查询

 SELECT   count(od_rid)
 FROM     od_f
 WHERE    od_f.plan_qty != od_f.cmp_qty
 GROUP BY od_f.ob_oid

我无法添加上述where语句,因为它会影响我的结果 我真的不知道该怎么做,将这些查询组合成一个子查询?某种联盟?我迷失了怎么做。
 感谢您的帮助

3 个答案:

答案 0 :(得分:1)

您可以根据需要使用条件聚合。虽然COUNT() CASE可能就足够了,但我最好的猜测是COUNT(DISTINCT)

SELECT   od_f.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value,
         COUNT(DISTINCT CASE WHEN od_f.plan_qty <> od_f.cmp_qty THEN od_f. od_rid END) as newcol
FROM od_f JOIN
     om_f
     ON od_f.ob_oid = om_f.ob_oid
GROUP BY od_f.ob_oid, total_value
ORDER BY Percent_Cmp desc;

您还应该学会使用正确的,明确的JOIN语法。简单的规则:从不FROM子句中使用逗号。

答案 1 :(得分:1)

@GordonLinoff解决方案对您有好处,但只有当您想要计算唯一的od_rid时,此解决方案适用于这两种情况,使用相关查询:

SELECT   t.ob_oid Order,
         Sum(plan_qty) Plan_Units,
         sum(cmp_qty) Completed_Units,
         Round(((Sum(cmp_qty)/sum(plan_qty)) * 100.00),2)Percent_Cmp,
         total_value Value,
         SUM(round(cmp_qty * unit_price,2)) cmp_value,
         (SELECT  count(f2.od_rid) FROM od_f f2
          WHERE f2.plan_qty != f2.cmp_qty and f2.ob_oid = f.ob_oid) as newcolumn
FROM     od_f t
         INNER JOIN om_f
ON       t.ob_oid = om_f.ob_oid
GROUP BY t.ob_oid, total_value
ORDER BY Percent_Cmp desc

答案 2 :(得分:0)

根据我的理解,您只需要plan_qty不等于cmp_qty的行数,请尝试以下操作:

SELECT   t.ob_oid                                       AS order,
         SUM(plan_qty)                                  AS plan_units,
         SUM(cmp_qty)                                   AS completed_units,
         ROUND(((SUM(cmp_qty)/SUM(plan_qty)) * 100),2)  AS percent_cmp,
         total_value                                    AS value,
         SUM(ROUND(cmp_qty * unit_price,2))             AS cmp_value,
         SUM(DECODE(plan_qty, cmp_qty, 0, 1))           AS rows_left
FROM     od_f t
         INNER JOIN om_f
            ON t.ob_oid = om_f.ob_oid
GROUP BY t.ob_oid, total_value
ORDER BY percent_cmp DESC;