简体   繁体   中英

SQL How to return All products sold in last 30 days Include non sellers

I am trying return a best sellers list for the last 30 days for a category ordered by sum quantity

If the category has 10 products and only 5 have sold I want to return all 10 products ordered by most sold.

Here's what I have so far

SELECT ROW_NUMBER() OVER
    (
    ORDER BY 
     ISNULL(SUM(B.quantity),0) desc
         )AS RowNumber
,
a.productID, 
ISNULL(SUM(B.quantity),0) AS countquantity,
a.product

FROM
products a
left join savedDetails b on a.productid =b.productid
left join Category d on d.Categorysec = a.CategoryID 

WHERE 
(a.pinstock='1' and a.BrandID = '7' and a.categoryid = '15' and (b.despatchdate >= DATEADD(DAY,-30,GETDATE()) OR b.despatchdate IS NULL))

GROUP BY 
a.productid,
a.CategoryID, 
a.product

Just need some help as this only returns products sold or never sold. If a product sold 32 days again it doesn't get returned.

Thanks

Move this clause:

and (b.despatchdate >= DATEADD(DAY,-30,GETDATE())

To the first left join clause. Putting it in the where clause makes SQL Server evaluate values on actual rows, turning your left join into an inner join. (This also makes the IS NULL check redundant.)

So:

...
FROM
products a
left join savedDetails b on a.productid =b.productid
    and (b.despatchdate >= DATEADD(DAY,-30,GETDATE())
left join Category d on d.Categorysec = a.CategoryID 
WHERE 
(a.pinstock='1' and a.BrandID = '7' and a.categoryid = '15'
GROUP BY 
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM