我想要上周售罄的前 3 件产品。
这是我的 sql 查询。
select ProductId,sum(Quantity) as quantity,createdOn from
(SELECT inv.Id,invd.ProductId, invd.Quantity ,cast (inv.CreatedOn as date) as createdOn FROM Invoice as inv
INNER JOIN
InvoiceDetail invd
ON
invd.InvoiceId = inv.id
WHERE inv.CreatedOn >= DATEADD(day,-11117, GETDATE()) ) as tbl
group by createdOn , ProductId
ORDER BY createdOn DESC
但每次约会我都没有获得前 3 个产品。如果我使用 TOP 3,那么它只会提供排名前 3 的产品,而我希望上周每天提供排名前 3 的产品。
最佳答案
如果我理解正确,您可以将 Row_number
与 windows function 一起使用每天获取前 3 个数量
。
每天按createdon
生成行数,基于quantity
列从高到低的顺序。
;WITH CTE AS(
SELECT productid,quantity,createdon,Row_number() over(partition by createdon ORDER BY quantity DESC,productid DESC) as RN
FROM
(
SELECT invd.productid,
sum(invd.quantity) as quantity,
cast(inv.createdon AS date) AS createdon
FROM invoice AS inv INNER JOIN invoicedetail invd
ON invd.invoiceid = inv.id
WHERE inv.createdon >= dateadd(day,-11117, getdate())
GROUP BY cast(inv.createdon AS date), invd.productid
) AS tbl
)
SELECT *
FROM CTE
WHERE RN <= 3
[结果]:
| productID | quantity | createdon | rn |
|-----------|----------|------------|----|
| 94 | 7 | 2018-07-25 | 1 |
| 1119 | 2 | 2018-07-25 | 2 |
| 1115 | 2 | 2018-07-25 | 3 |
| 94 | 4 | 2018-07-26 | 1 |
| 1117 | 2 | 2018-07-26 | 2 |
| 1114 | 2 | 2018-07-26 | 3 |
关于根据最近 7 天内的日期查询前 3 名售罄产品的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51555476/