如何在使用连接时区分sum()

时间:2014-03-10 09:58:47

标签: mysql sql group-by sum distinct

我有2张桌子。 一个保存OK部件的数据,另一个保存拒绝的数据。

我喜欢以下列格式接收数据:

| YYYY-MM | SUM(ok.qty) | SUM(reject.qty) | reject % |

1)是否可以使用JOIN然后某种DISTINCT sum(ok.qty)

SELECT 
    DATE_FORMAT(date, '%Y-%m'), 
    SUM(ok.qty), 
    SUM(reject.qty), 
    SUM(reject.qty) / SUM(reject.qty + ok.qty) as reject_percent
FROM ok
JOIN reject ON ok.id = reject.ok_id
GROUP BY DATE_FORMAT(date, '%Y-%m')

2)如果不是如何消除重复的子查询?

SELECT 
    DATE_FORMAT(date, '%Y-%m'), 
    SUM(ok.qty), 
    (SELECT qty FROM reject WHERE ok_id = ok.id), 
    (SELECT qty FROM reject WHERE ok_id = ok.id) / 
        ( (SELECT qty FROM reject WHERE ok_id = ok.id) + SUM(ok.qty) ) 
        as reject_percent
FROM ok
GROUP BY DATE_FORMAT(date, '%Y-%m')

现在必须写3次查询。

数据库设计:

ok.id可能有多次拒绝。

Database

1 个答案:

答案 0 :(得分:1)

你可以尝试这样..

SELECT 
    DATE_FORMAT(date, '%Y-%m'), 
    SUM(ok.qty), 
    SUM(reject.qty), 
    ((SUM(reject.qty) / SUM(reject.qty + ok.qty))*100)as reject_percent
FROM ok
inner JOIN (Select Ok_Id,Sum(qty) as qty from Reject group by OK_id) as reject ON ok.id = reject.ok_id
GROUP BY DATE_FORMAT(date, '%Y-%m')