نوشته شده توسط
mr.sirwan
......
اما مسئله ای که الان با این کد دارم اینه که من میخوام تمامی کالاها رو واکشی کنم حتی اونایی که هیچ فروشی طی این دو سال نداشته باشن، ولی این کوئری فقط اونایی که فروشی داشتن رو واکشی میکنه، میدونم به این دلیله که داریم از جدول فروشها عمل واکشی رو انجام میدیم اما میخواستم بدونم ایا راهی هست که کالاهایی که فروشی نداشتن رو هم بشه توسط این کوئری واکشی کرد؟
در کوئری قبل، جدول کالا را با نتیجه مجموع فروش left join کنید
به صورت زیر
declare @d1from as date;
set @d1from = '2018/03/21'; -- آغاز سال 1397
declare @d1to as date;
set @d1to = '2019/03/21'; -- آغاز سال 1398
declare @d2from as date;
set @d2from = '2019/03/21'; -- آغاز سال 1398
declare @d2to as date;
set @d2to = '2020/03/21'; -- آغاز سال 1399
with cte_Sales
AS
(
select
sales.ProductId,
sales.QUANTITY,
sales.SalesDate,
sales.TotalPrice,
(case when (SalesDate>=@d1from and SalesDate<@d1to) then 'year1'
when (SalesDate>=@d2from and SalesDate<@d2to) then 'year2' else null end) as gLabel
from sales
where (SalesDate>=@d1from and SalesDate<@d1to) OR (SalesDate>=@d2from and SalesDate<@d2to)
),
cte_allProductSales
AS
(
select
Product.ProductId,
Product.Name,
SUM(cte_Sales.TotalPrice) AS SumOfTotalPrice,
cte_Sales.gLabel
from Product left join cte_Sales on Product.ProductId = cte_Sales.ProductId
group by
Product.ProductId,
Product.Name,
cte_Sales.gLabel
)
select
ProductId,
ISNULL([year1] , 0) AS YEAR1,
ISNULL([year2] , 0) AS YEAR2,
ISNULL([year2],0)-ISNULL([year1],0) as Diff
from cte_allProductSales
PIVOT
( SUM(SumOfTotalPrice)
FOR gLabel IN ([year1],[year2])
) pivotResualt
کوئری زیر هم همان نتیجه رو میده و فکر کنم performance بهتری داشته باشه
declare @d1from as date;
set @d1from = '2018/03/21'; -- آغاز سال 1397
declare @d1to as date;
set @d1to = '2019/03/21'; -- آغاز سال 1398
declare @d2from as date;
set @d2from = '2019/03/21'; -- آغاز سال 1398
declare @d2to as date;
set @d2to = '2020/03/21'; -- آغاز سال 1399
select
ssssss.*,
ssssss.year2-ssssss.year1 as diff
from
(
select
Product.ProductId,
SUM(case when Sales.ProductId=Product.ProductId AND SalesDate>=@d1from and SalesDate<@d1to then sales.totalPrice else 0 end) as year1,
SUM(case when Sales.ProductId=Product.ProductId AND SalesDate>=@d2from and SalesDate<@d2to then sales.totalPrice else 0 end) as year2
from Product, Sales
group by Product.ProductId
) ssssss