2014-10-28 33 views
0
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行数与设备行相匹配。我会怎么做?使用加入计数在计算中选择

+0

可你只是返回'COUNT(c.object_row_id)'本'select',做在客户端上? – akonsu 2014-10-28 07:15:18

回答

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 
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避免被零除。

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