簡體   English   中英

SQL JOIN,GROUP BY對四個表進行記錄

[英]SQL JOIN, GROUP BY on Four tables to get Record

我繼承了以下數據庫設計。 表是:

auth_user
----------
first_name
last_name

staffuser
----------
phone_number
user_id

billing_customerservicebill
-----------------------------
bill_id
service_provider_id
discounted_price

billing_billmanagement
------------------------
creation_date

我的查詢需要按月返回每個用戶的Discounted_price的總和。 結果不准確。
以下查詢使我得出的總和值正確,但是first_name的前面不正確:

select a.service_provider_id, first_name, sum(a.discounted_price) As total
from billing_customerservicebill a,
     users_staffuser b,
     billing_billmanagement c,
     auth_user d 
where a.service_provider_id = b.id
  AND d.id = b.id
  AND a.bill_id = c.id
  AND c.creation_date between '2017-12-01' AND '2017-12-31'
group by first_name, service_provider_id
order by 1



 My data show in Table Currently 
    service_provider_id | first_name | total
      5                      suneel      500
      8                      Ali         900
 Expected data is
service_provider_id | first_name | total
      5                      suneel      1000
      8                      Ali         500

@MatBailie這是我進行的查詢。

select a.service_provider_id, first_name, Sum(a.discounted_price)
        from billing_customerservicebill a
             left outer join users_staffuser b
             on a.service_provider_id = b.id
             left outer join billing_billmanagement c
             on a.bill_id = c.id
             left outer join auth_user d 
             on d.id = b.user_id
        where c.creation_date between '2017-12-01' AND '2017-12-31'
        group by service_provider_id, first_name
        order by 1

b.id = d.id和service_provider_id = b.id是auth_user id = service_provider_id嗎? mb你應該重新檢查嗎?

嘗試執行並檢查表連接是否正確的數字:

select a.service_provider_id, first_name, a.discounted_price from billing_customerservicebill a left outer join users_staffuser b on a.service_provider_id = b.id left outer join billing_billmanagement c on a.bill_id = c.id left outer join auth_user d on d.id = b.id where c.creation_date between '2017-12-01' AND '2017-12-31' order by 1

完成后,確定字段中的數字,然后對其求和

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM