寻找 JOIN 或嵌套查询,通过它我可以获取 Providers 数据列表,如下所述

Looking for JOIN or nested query by which I can get the list of Providers data as mentioned below needs

Table:用户

|_id|name    |
|---|--------|
|115|Abhalo  |
|106|vesiy   |

注:-这里_id是用户table.

的主键

Table:乘车

|_id|total_fair|provider_id|is_admin_paid|
|---|----------|-----------|-------------|
|267|     480.0|        115|            0|
|370|      60.0|        106|            1|
|258|     200.0|        115|            1|

注:-这里provider_id是来自用户table.

的外键

输出:- 在这里,我必须使用 is_admin_paid 标志来获取总数 paid_amount 和总计 unpaid_amount.

需要输出:-

|provider_id|driver_name|total_rides|paid_amount|unpaid_Amount|
|-----------|-----------|-----------|-----------|-------------|
|        115|     Abhalo|          2|        200|          480|
|        106|      Vesiy|          1|         60|            0|

我是 PostqreSQL 的初学者。而面对这种情况的上市数据。现在不想为 paid_amount 和 unpaid_amount.

使用循环

提前谢谢你。非常感谢您花时间查看我的问题。

select r.provider_id, u.name as driver_name,
       count(*) as total_rides,
       sum(case when r.is_admin_paid = 1 then total_fair else 0 end) as paid_amount,
       sum(case when r.is_admin_paid = 0 then total_fair else 0 end) as unpaid_amount
from users u
join rides r on r.provider_id = u._id
group by r.provider_id, u.name
SELECT R.provider_id, 
       U.name as driver_name,
       count(*) as total_rides,
       sum(case when R.is_admin_paid = 1 then total_fair else 0 end) as paid_amount,
       sum(case when R.is_admin_paid = 0 then total_fair else 0 end) as unpaid_amount
FROM users U JOIN Rides R 
ON R.provider_id = U._id
GROUP BY R.provider_id , U.name
ORDER BY count(*) DESC

这里有一个例子:Example