表:用戶
|_id|name |
|---|--------|
|115|Abhalo |
|106|vesiy |
注意:-這里_id是用戶表的主鍵。
表:游樂設施
|_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 是用戶表中的外鍵。
輸出:-這里我必須使用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 使用回圈。
先感謝您。我非常感謝您抽出時間來查看我的問題。
uj5u.com熱心網友回復:
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
這是它的示例:示例
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478059.html
標籤:数据库 PostgreSQL 加入 左连接 psql
