在SQL中选择前n行会给出错误的结果

时间:2018-03-17 16:20:00

标签: sql sql-server

我有两个表,ProductSalesProduct

Product表样本记录(此处ProductID是主键):

ProductID | ProductCode | Name
----------+-------------+-----------
1               P001      Computer
2               p002      Laptop
3               p003      Speaker

SalesProduct表样本记录(此处ID是主键,ProductID是引用Products表的外键:

ID| SalesNo | ProductID  
--+---------+-----------
1   S0001         1
2   S0002         2
3   S0003         3
4   S0004         1
5   S0005         2
6   S0006         3
7   S0007         1
8   S0008         2
9   S0009         3

当我写这个查询时:

SELECT  
    SalesNo, SalesProduct.ProductID, Name 
FROM 
    SalesProduct
JOIN 
    Product ON SalesProduct.ProductID = Product.ProductID

它会正常工作并返回此结果:

SalesNo | ProductID | Name
--------+-----------+---------
S0001         1       Computer
S0002         2       Laptop
S0003         3       Speaker
S0004         1       Computer
S0005         2       Laptop
S0006         3       Speaker
S0007         1       Computer
S0008         2       Laptop
S0009         3       Speaker

但是当我尝试选择这样的TOP(3)行时:

SELECT TOP(3) 
    SalesNo, SalesProduct.ProductID, Name 
FROM 
    SalesProduct
JOIN 
    Product ON SalesProduct.ProductID = Product.ProductID

此查询将返回相同的产品:

S0001   1   Computer
S0004   1   Computer
S0007   1   Computer

但我想要这个结果:

S0001         1       Computer
S0002         2       Laptop
S0003         3       Speaker

上述查询有什么问题?我怎样才能获得预期的输出?

3 个答案:

答案 0 :(得分:1)

您未获得预期输出可能是因为您没有指定Order By Clause。您可以执行以下任一操作

SELECT TOP 3 
    SalesNo, SalesProduct.ProductID, Name 
FROM 
    SalesProduct
JOIN 
    Product ON SalesProduct.ProductID = Product.ProductID
ORDER BY SalesNo ASC

或喜欢这个

;WITH CTE
AS
(
SELECT 
RN = ROW_NUMBER() OVER(ORDER BY  SalesNo),
        SalesNo, SalesProduct.ProductID, Name 
    FROM 
        SalesProduct
    JOIN 
        Product ON SalesProduct.ProductID = Product.ProductID

)
SELECT
SalesNo, SalesProduct.ProductID, Name 
WHERE RN<4 

答案 1 :(得分:0)

SELECT TOP(3) sp.SalesNo, sp.ProductID, p.Name 
FROM SalesProduct sp
INNER JOIN Product p ON SalesProduct.ProductID = Product.ProductID
ORDER BY sp.SalesNo

答案 2 :(得分:0)

请试试这个

DECLARE @Product TABLE (ProductId INT,ProductCode VARCHAR(10), Name VARCHAR(100))
INSERT INTO @Product(ProductId,ProductCode,Name) 
(SELECT 1,'P001','Computer' UNION ALL SELECT 2,'P002','LAPTOP' UNION ALL SELECT 3,'P003','Speaker')

DECLARE @SalesProduct TABLE (Id INT,SalesNo VARCHAR(10),ProductId INT)
INSERT INTO @SalesProduct
SELECT 1,'S0001',1 UNION ALL SELECT 2,'S0002',2 UNION ALL SELECT 3,'S0003',3 UNION ALL SELECT 4,'S0004',1
UNION ALL SELECT 5,'S0005',2 UNION ALL SELECT  6,'S0006',3 UNION ALL SELECT 7,'S0007',1 UNION ALL SELECT 8,'S0008',2
UNION ALL SELECT 9,'S0009',3

SELECT TOP(3) 
    SP.SalesNo, SP.ProductID, P.Name 
FROM 
    @SalesProduct SP
INNER JOIN 
    @Product P ON SP.ProductID = P.ProductID
ORDER BY SP.SalesNo