我有一个表,给出了每个客户的价值总和,我想要的是按月按客户制作销售报告,但是有些客户在某个月没有购买任何东西,尽管我希望他们以0值出现,以与当前月份进行比较。
;with Months AS
(SELECT 1 AS MonthNum
UNION ALL
SELECT MonthNum + 1 as MonthNum FROM Months WHERE MonthNum <12)
select c.client_id,Months.MonthNum 'Mês2021', sum(sales) 'v' from fact_table as c cross join Months
where Months.MonthNum=month(c.date)
and year(c.date)=2021 group by c.intCodEntidade,Months.MonthNum order by c.client_id,Months.MonthNum
但是它不返回我想要的空值,相反,它过滤并且不显示空值。
请heelp。
你没有解释得很好,但让我们假设这是你的最小可复制示例:
declare @fact_table as table (
[date] datetime,
client_id int,
sales money
)
insert into @fact_table values ('26/09/21', 1, 10)
insert into @fact_table values ('26/10/21', 1, 15)
;with Months AS
(SELECT 1 AS MonthNum
UNION ALL
SELECT MonthNum + 1 as MonthNum FROM Months WHERE MonthNum <12)
select c.client_id,Months.MonthNum 'Mês2021', sum(sales) 'v' from @fact_table as c cross join Months
where Months.MonthNum=month(c.date)
and year(c.date)=2021
group by c.client_id,Months.MonthNum
order by c.client_id,Months.MonthNum
结果(这对你来说是错误的)是:client_id | Mês2021 |----------- | ----------- | ---------------------1 | 9 | 100001 | 10 | 15,00
并且您希望所有客户在每个月都出现。是吗?如果是这样,也许你的问题的解决办法是加入"客户"。表:
declare @fact_table as table (
[date] datetime,
client_id int,
sales money
)
declare @clients as table (
client_id int
)
insert into @fact_table values ('26/09/21', 1, 10)
insert into @fact_table values ('26/10/21', 2, 15)
insert into @clients values (1)
insert into @clients values (2)
;with Months AS
(SELECT 1 AS MonthNum
UNION ALL
SELECT MonthNum + 1 as MonthNum FROM Months WHERE MonthNum <12)
select l.client_id,m.MonthNum 'Mês2021', isnull(sum(sales),0) 'v'
from @clients l cross join Months m
left join @fact_table c
on l.client_id = c.client_id and m.MonthNum=month(c.date) and year(c.date)=2021
group by l.client_id,m.MonthNum
order by l.client_id,m.MonthNum
它会返回这个:
<表类>client_id Mes2021 v tbody><<tr>1 1 0, 00 12 0, 00 13 0, 00 14 0, 00 15 0, 00 16 0, 00 17 0, 00 18 0, 00 19 10, 00 110 0, 00 111 0, 00 112 0, 00 21 0, 00 22 0, 00 23 0, 00 24 0, 00 25 0, 00 26 0, 00 27 0, 00 28 0, 00 29 0, 00 210 15日00 211 0, 00 212 0, 00 表类>