我正在尝试按照总和数量
返回过去30天的最佳卖家列表如果该类别有10个产品且只有5个已售出,我想退回所售出的所有10个产品。
这是我到目前为止所拥有的
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
只需要一些帮助,因为这只会退回已售出或未售出的产品。如果产品再次销售32天,则无法退货。
由于
答案 0 :(得分:5)
移动此条款:
and (b.despatchdate >= DATEADD(DAY,-30,GETDATE())
到第一个左连接子句。将它放在where子句中会使SQL Server评估实际行的值,将左连接转换为内连接。 (这也使IS NULL
检查变得多余。)
所以:
...
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
...