繁体   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