gpt4 book ai didi

mysql - SQL JOIN, GROUP BY 四张表获取按月记录

转载 作者:搜寻专家 更新时间:2023-10-30 20:23:55 24 4
gpt4 key购买 nike

我有以下数据库设计。表格是:

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 总和。我需要每个月的记录显示在列中。下面的查询给我 This record

select a.service_provider_id, first_name, Sum(a.discounted_price), EXTRACT(MONTH FROM c.creation_date)
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-11-01' AND '2017-12-31'
group by service_provider_id, first_name, EXTRACT(MONTH FROM c.creation_date)
order by 1

My data show in Table Currently
service_provider_id | first_name | Sum | Month
5 | suneel 31500 | 11
5 | Suneel | 900 | 12

Expected data is
service_provider_id | first_name | Nov | December
5 | suneel | 31500 | 900

最佳答案

最灵活的方法是使用条件聚合...

select
a.service_provider_id,
first_name,
SUM(CASE WHEN c.creation_date >= '2017-11-01' AND c.creation_date < '2017-12-01' THEN a.discounted_price END) AS nov,
SUM(CASE WHEN c.creation_date >= '2017-12-01' AND c.creation_date < '2018-01-01' THEN a.discounted_price END) AS dec
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-11-01' AND '2017-12-31'
group by service_provider_id, first_name
order by 1

这表明您需要提前知道要计算哪些列。

关于mysql - SQL JOIN, GROUP BY 四张表获取按月记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com