[英]SQL: How to return revenue for specific year
我想為所有客戶顯示特定年份的收入,無論他們是否有特定年份的收入數據。 (如果他們沒有特定年份的數據,則可以使用“無數據”之類的填充詞)
示例數據如下所示:
表格1
顧客 | 價格 | 數量 | 訂購日期 |
---|---|---|---|
xxx | 12 | 5個 | 1990/03/25 |
yyy | 15 | 7 | 1991/05/35 |
xxx | 34 | 2個 | 1990/08/21 |
所需的 Output 看起來有點像這樣:
顧客 | 收入(1990 年) |
---|---|
xxx | 128 |
yyy | 沒有數據 |
獲得每個的總收入將是:
SELECT 客戶,
SUM(數量*價格) AS 收入
但我 go 如何為所有客戶列出特定年份的信息? (包括沒有特定年份數據的客戶)
我們可以使用 CTE 或子查詢來創建所有客戶的列表,並使用另一個來獲取所有年份並將它們交叉連接並左連接到收入中。 這為每年的每個客戶提供了一行。 如果你添加 where y= 你將只會得到請求的年份。
CREATE TABLE revenue( Customer varchar(10), Price int, Quantity int, OrderDate date);
insert into revenue values ('xxx', 12,5,'2021-03-25'), ('yyy', 15,7,'2021-05-15'), ('xxx', 34,2,'2022-08-21');
with cust as (select distinct customer c from revenue), years as (select distinct year(OrderDate) y from revenue) select y "year", c customer, sum(price*quantity) revenue from years cross join cust left join revenue r on cust.c = r.customer and years.y = year(OrderDate) group by c,y, year(OrderDate) order by y,c
年份 | 客戶 | 收入 ---: |:-------- | ------: 2021 | xxx | 60 2021 | 年年 | 105 2022 | xxx | 68 2022 | 年年 | null
db<> 在這里擺弄
您只需使用 group by 並在子查詢中進行求和,然后將其加入您的客戶表。 IE:
select customers.Name, totals.Revenue
from Customers
Left join
( select customerId, sum(quantity*price) as revenue
from myTable
where year(orderDate) = 1990
group by customer) totals on customers.CustomerId = myTable.customerId;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.