What is the use of WITH TIES keyword in SELECT statement in SQL Queries?

前端 未结 7 1436
醉梦人生
醉梦人生 2021-01-30 20:15
SELECT TOP 5 WITH TIES EmpNumber,EmpName 
FROM Employee 
Order By EmpNumber DESC

This above query return more than five result, What is the use of \"Wi

7条回答
  •  梦谈多话
    2021-01-30 20:33

    From here

    Using TOP WITH TIES to include rows that match the values in the last row

    If you want to use TOP WITH TIES you must use order by.

    Create Table

    CREATE TABLE [dbo].[Products](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ProductName] [nvarchar](50) NULL,
    [Price] [float] NULL) 
    GO
    

    The following illustrates the INSERT statement that inserts rows into an existing table

    INSERT INTO [dbo].[Products] VALUES ('Bicycle 1' , 258.2)
    INSERT INTO [dbo].[Products] VALUES ('Bicycle 2' , 265.3)
    INSERT INTO [dbo].[Products] VALUES ('Bicycle 3' , 267.8)
    INSERT INTO [dbo].[Products] VALUES ('Bicycle 4' , 268.9)
    INSERT INTO [dbo].[Products] VALUES ('Bicycle 5' , 267.9)
    INSERT INTO [dbo].[Products] VALUES ('Bicycle 6' , 267.9)
    GO
    

    then

    SELECT TOP 4 WITH TIES
    ProductName, Price
    FROM Products
    ORDER BY Price
    

    In this example, the two expensive product has a list price of 267.9. Because the statement used TOP WITH TIES, it returned one more products whose list prices are the same as the forth one.

提交回复
热议问题