如何从两个表计算百分比?

时间:2018-08-31 11:48:38

标签: mysql sql database select

请帮我从两个表中计算客户数量的百分比,这两个表在2018年1月1日至2018年1月5日之间付款。

const express = require('express');

const router = express.Router();

const Post = require('../../models/Post');

router.all('/*',(req, res, next)=>{

    req.app.locals.layout='admin';
    next();
});

router.get('/',(req, res)=>{

    res.send('It  Works');
});

router.get('/create',(req, res)=>{

    res.render('admin/posts/create');

});

// router.post('/create',(req, res)=>{

//     res.send('worked');

// });

router.post('/create', (req, res)=>{

    let allowComments=true;
    if(req.body.allowComments){
        allowComments=true;   
    }else{
        allowComments=false;

}

   const newPost = Post({
            title: req.body.title,
            status: req.body.status,
            allowComments:allowComments,
            body: req.body.body
    });
    newPost.save().then(savedPost=>{
        res.redirect('/admin/posts');
    }).catch(error=>{
        console.log('could not post');
    });
    // console.log(req.body);
});

module.exports=router;    

第二张桌子

clients

client_id  sum     date
100      2400   01.01.2018
101      2550   02.01.2018
120      2345   05.01.2018
155      5526   30.03.2018

我写了这样的查询,但是不能正常工作:

payments 

client_id   total  date
100        47    01.01.2018
101        50    02.01.2018
120        0    05.01.2018
155        20    30.03.2018

谢谢!

2 个答案:

答案 0 :(得分:1)

使用加入,我想您想根据日期计算总付款百分比

SELECT p.date ,
( sum(p.total) /sum(c.sum)) * 100.00) AS percent
FROM payments p join  clients  c on p.client_id=c.client_id
WHERE
p.date between '2018-01-01' 
and '2018-01-05' 
GROUP BY
p.date

答案 1 :(得分:0)

更新

计算与客户的付款比率。我不知道如何使用JOIN做到这一点。

SELECT 100 * COUNT(DISTINCT p.id) / (SELECT COUNT(*)
                                     FROM clients 
                                     WHERE date between '2018-01-01' and '2018-01-31') as 'Percent' 
FROM Payments p
WHERE p.date between '2018-01-01' and '2018-01-31'

计算每个表的总和将两个表连接在client_id和date上

SELECT 100 * SUM(p.total) / SUM(c.sum) as 'Percent'
FROM Payments p
JOIN clients c ON p.client_id = c.client_id AND p.date = c.date
WHERE p.date between '2018-01-01' and '2018-01-05'

百分比
2.1933

如果要按日期添加GROUP BY,则

SELECT p.date as 'Date', 100 * SUM(p.total) / SUM(c.sum) as 'Percent'
FROM Payments p
JOIN clients c ON p.client_id = c.client_id AND p.date = c.date
WHERE p.date between '2018-01-01' and '2018-01-05' 
GROUP BY p.date

日期百分比
2018-01-01 1.9583
2018-01-02 1.9608
2018-01-05 2.6866