我基本上在使用三張桌子;第一個:月/年日歷,第二個:客戶資料(與自身有父/子關系),第三個:銷售資料。我希望能夠在一個日期范圍內顯示每個客戶每個月的銷售額,而不管一個或多個客戶可能沒有銷售的月份。
我可以獲得查詢以顯示我的范圍內的每個月/年,并計算銷售月份的銷售總額。但是,由于帳號是通過一個沒有每個月的值的表加入日歷的,所以我不知道如何列出銷售額為空的賬戶。
到目前為止我最接近的:
with cumulative as (
select MONTH(s.docdate) [Month]
, YEAR(s.docdate) [Year]
, s.account [Account]
, sum(s.amount) [sales]
from sales s
group by MONTH(s.docdate), YEAR(s.docdate), s.account
)
select c.monthno [Month]
, c.year [Year]
, (select account from customers where account=s.account) [Account]
, s.sales
from cumulative s
right join calendar c
on datefromparts(s.year, s.month, 1) = datefromparts(c.year,c.monthno,1)
order by c.year, c.monthno
結果是;
Month Year Account sales
1 2020 1 25
1 2020 2 90
2 2020 null null
3 2020 3 45
3 2020 4 65
4 2020 null null
5 2020 1 120
5 2020 2 45
6 2020 null null
7 2020 null null
etc.
此處設定示例:https ://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b8ae260f2901693bf4cca75fb2451649
如果我嘗試使用左連接或右連接來引入客戶表,則會將結果折疊到只有月份和具有銷售值的帳戶。
with cumulative as (
select MONTH(s.docdate) [Month]
, YEAR(s.docdate) [Year]
, s.account [Account]
, sum(s.amount) [sales]
from sales s
group by MONTH(s.docdate), YEAR(s.docdate), s.account
)
select c.monthno [Month]
, c.year [Year]
, c2.account [Account]
, s.sales
from cumulative s
right join calendar c
on datefromparts(s.year, s.month, 1) = datefromparts(c.year,c.monthno,1)
right join customers c2
on s.account=c2.account
order by c.year, c.monthno
給出:
Month Year Account sales
1 2020 1 25
1 2020 2 90
3 2020 3 45
3 2020 4 65
5 2020 2 45
5 2020 1 120
1 2021 2 75
我想看到的輸出:
Month Year Account sales
1 2020 1 25
1 2020 2 90
1 2020 3 null
1 2020 4 null
2 2020 1 null
2 2020 2 null
2 2020 3 null
2 2020 4 null
如何從客戶那里獲取每個帳號以顯示在日歷中的每個月?
uj5u.com熱心網友回復:
如果您將日歷和客戶與交叉聯接結合起來,您將獲得一組完整的帳戶和日期。將其設為 CTE,然后使用您的累積 CTE 收集這些結果。現在,您可以從帶有左連接銷售資料的 Calendar/Customers 表中進行選擇:
with BaseTable
as (
select c.MonthNo as Month
, c.Year
, cust.Account
from [CALENDAR] c
cross join Customers cust
), cumulative as (
select MONTH(s.docdate) [Month]
, YEAR(s.docdate) [Year]
, s.account [Account]
, sum(s.amount) [sales]
from sales s
group by MONTH(s.docdate), YEAR(s.docdate), s.account
)
select bt.Month
, bt.Year
, bt.Account
, c.sales
from BaseTable bt
left join cumulative c
on c.month = bt.Month
and c.Year = bt.Year
and c.Account = bt.Account
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/443363.html
上一篇:SQL:從2個條件中選擇MAX值
