仅退回第10件商品的商品

时间:2017-07-04 01:37:19

标签: sql-server

我需要编写一个只返回具有第10个totalSale值的项的查询。我知道我可以用TOP来获得前10个项目,但我希望它只显示第10个项目。这是我写的查询:

SELECT TOP 10 D_I.ID, SUM(F_S.Sale) AS TOTALSALE 
FROM Dim_ItemsD_I JOIN FCT_Sales F_S ON D_I.ID = F_S.ID
GROUP BY D_I.ID 

请帮忙!谢谢

3 个答案:

答案 0 :(得分:1)

您需要使用子查询。按降序排序前10个项目,然后选择第一个项目:

 select top 1 ITEM, TOTALSALE 
 from
    (select top 10 D_I.ITEM, SUM(F_S.Sale) as TOTALSALE 
     from Dim_Items D_I
     join FCT_Sales F_S on D_I.ID = F_S.Item_ID
     group by D_I.Item 
     order by TOTALSALE DESC) T

点击此处查看简化示例:http://rextester.com/live/SAOQ22288

答案 1 :(得分:1)

您可以在此处使用ROW_NUMBER

SELECT t.ID, t.TOTALSALE
FROM
(
    SELECT
        D_I.ID,
        SUM(F_S.Sale) AS TOTALSALE,
        ROW_NUMBER() OVER (ORDER BY SUM(F_S.Sale) DESC) rn
    FROM Dim_Items D_I
    JOIN FCT_Sales F_S
        ON D_I.ID = F_S.ID
    GROUP BY D_I.ID
) t
WHERE t.rn = 10;

答案 2 :(得分:1)

SELECT D_I.ID, SUM(F_S.Sale) AS TOTALSALE      
FROM Dim_ItemsD_I 
JOIN FCT_Sales F_S 
ON D_I.ID = F_S.ID 
GROUP BY D_I.ID 
Offset 9 rows fetch next 1 rows only
Order by TotalSale

偏移将跳过前9行,接下来将选择1行。根据您的要求,按照asc或desc订购。