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

x4shl7ld  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(452)

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

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

第二张table

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

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

SELECT (COUNT(distinct payments.client_id) / (COUNT(distinct 
clients.client_id)) * 100) AS percent, payments.date 
FROM payments, clients WHERE
payments.date between '2018-01-01' 
and '2018-01-05' 
GROUP BY
(payments.date);

谢谢!

pkbketx9

pkbketx91#

更新
计算付款与客户的比率。我不知道如何使用连接来实现这一点。

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
如果要按日期添加分组依据

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

jhiyze9q

jhiyze9q2#

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

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

相关问题