根据最近 7 天内的日期查询前 3 名售罄产品的 SQL 查询

标签 sql sql-server

我想要上周售罄的前 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 的产品。

这是我的输出。 但我每天只需要 3 条记录。 enter image description here

预期输出: enter image description here

最佳答案

如果我理解正确,您可以将 Row_numberwindows 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

sqlfiddle

[结果]:

| 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/

相关文章:

sql - SQL Server 数据库 ID 始终为正吗?

c++ - 为什么查询有歧义符号?

sql-server - SQL Server : implicit data type conversions chart

mysql - INNER JOIN 仅显示表中的第一行

c# - 使用 MVC2 从 SQL 数据库动态调整图像大小

SQL Server 解析 JSON 来更新另一个表

c# - EF Core 日期时间偏移

php - 无法通过 PHP 连接到 MSSQL

sql - 在 SQL Server 中,什么是最有效的方法来确定我的数据在一个月中的哪个工作日和哪个星期

sql - 推荐一个很好的SQL Server临时表教程