我正在嘗試獲取所有客戶的串列以及他們從 1 月到 10 月每個月花了多少錢。
我有一個用戶表和一個訂單表。Orders 表有一個 user_id 欄位,它鏈接到 Users 表的 id,所以一個用戶可以有很多訂單,也可以沒有。
我有這個查詢,它會給我訂單數量和用戶在一月份花了多少錢。我該如何改變這一點,以便我可以得到一列,顯示每個月的訂單數量和總支出?此外,對于此查詢,對于 0 個訂單的用戶,我沒有得到任何結果。
select users.id, users.first_name, users.last_name, count(orders.id) as num_of_orders, sum(orders.total) as total_spent
from users
left join orders on users.id = orders.user_id
where orders.created_at between '2020-01-01 00:00:00' and '2020-01-31 23:59:00'
group by users.id
order by num_of_orders asc
uj5u.com熱心網友回復:
在您的查詢之上構建 - 構建一組月份周期 ( monthsCTE),orders按訂單的月份周期和users按 id 將其加入。按用戶和期間分組。我假設這users.id是一個主鍵,所以你不需要按其他users屬性分組。對于沒有訂單的月份/用戶,您也將獲得零結果。
with month_periods(m) as
(
select date_trunc('month', s)::date
from generate_series('2020-01-01'::timestamp, '2020-10-01', interval '1 month') s
)
select month_periods.m month_period, users.id, users.first_name, users.last_name,
count(orders.id) as num_of_orders, sum(orders.total) as total_spent
from month_periods
left join orders on date_trunc('month', orders.created_at)::date = month_periods.m
left join users on users.id = orders.user_id
group by users.id, month_periods.m
order by num_of_orders;
uj5u.com熱心網友回復:
您還需要按月/年分組:
select users.id
, users.first_name
, users.last_name
, count(orders.id) as num_of_orders
, sum(orders.total) as total_spent
, to_char(orders.created_at, 'yyyy-mm')
from users
left join orders on users.id = orders.user_id
group by users.id, users.first_name, users.last_name, to_char(orders.created_at, 'yyyy-mm')
order by num_of_orders asc
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341491.html
標籤:sql PostgreSQL
下一篇:計算平均人數
