在select中使用计算中的连接计数

时间:2014-10-28 07:06:20

标签: mysql sql join count

SELECT e.qty * e.unit_cost * e.unit_no * (e.factor/100) AS Ext_price, c.cost_type, c.cost_dt, c.internal_cost_amt, c.client_cost_amt
FROM equipment e
LEFT JOIN CostAllocation c ON (c.object_row_id = e.row_id)

我现在想要将Ext_price除以与设备行匹配的CostAllocation行数。我该怎么做?

3 个答案:

答案 0 :(得分:2)

SELECT e.qty*e.unit_cost*e.unit_no*e.factor/(100*x.cnt) AS Ext_price,
       c.cost_type,
       c.cost_dt,
       c.internal_cost_amt,
       c.client_cost_amt
FROM equipment e
LEFT JOIN CostAllocation c ON c.object_row_id = e.row_id
LEFT JOIN
  (SELECT row_id,
          count(*) cnt
   FROM CostAllocation
   GROUP BY row_id) x ON c.object_row_id = x.row_id

答案 1 :(得分:1)

尝试以下:

select  g.*,g.Ext_price/(select count(*) from CostAllocation k where k.object_row_id=g.row_id) as youranswer
from 
(
SELECT e.row_id,e.qty*e.unit_cost*e.unit_no*e.factor/100 AS Ext_price, c.cost_type, c.cost_dt, c.internal_cost_amt, c.client_cost_amt
FROM equipment e
LEFT JOIN CostAllocation c ON c.object_row_id = e.row_id)g

答案 2 :(得分:0)

由于mysql不支持分析函数,因此最简单的方法是添加子查询(未经测试):

SELECT Ext_price, cost_type, cost_dt, internal_cost_amt
     , client_cost_amt
     , Ext_price / ( nullif( (select count(1) 
                              from CostAllocation c2
                              where c2.object_row_id = e.row_id), 0) )
FROM (
    SELECT e.qty*e.unit_cost*e.unit_no*e.factor/100 AS Ext_price
         , c.cost_type, c.cost_dt, c.internal_cost_amt, c.client_cost_amt
    FROM equipment e
    LEFT JOIN CostAllocation c 
        ON c.object_row_id = e.row_id
) as T

我添加了nullif以避免被零除。