如何在没有前五条记录的情况下选择所有其他记录?

时间:2013-07-23 08:55:02

标签: sql sql-server sql-server-2008

Location    TotalRevenue    LocationID

Orugodawatta    10059135.78 OR
Kohuwala    7058537.73  KH
Koswaththa  6717136.02  KW
Havelock Town   5748932.59  HT
Negombo         5193678.33  NG
Induruwa    3017552.74  IA
Absdhku         2254281.21      AB

我在sql server 2008中有一个表。如何选择没有前5个记录的所有其他行? 如果我的表有100条记录,我可以选择所有其他95条记录而没有前5条记录。请帮帮我

5 个答案:

答案 0 :(得分:1)

试试这个。

SELECT * FROM MyTable WHERE LOCATION NOT IN (SELECT TOP 5 LOCATION FROM MyTable)

答案 1 :(得分:0)

SELECT * FROM tableName 
EXCEPT (SELECT TOP(5)* FROM tableName  )

您的整个查询。试一试

SELECT Location,[Total Revenue],LocationID
FROM
  (
    SELECT Location, SUM(SellingPrice) AS 'Total Revenue', LocationID 
    FROM BI_LocWiseTopItems 
    WHERE (GRNDate BETWEEN '' AND GETDATE()) 
    GROUP BY Location, LocationID ORDER BY 'Total Revenue' desc 
  ) AS temp
EXCEPT  (
    SELECT top(5)Location, SUM(SellingPrice) AS 'Total Revenue', LocationID 
    FROM BI_LocWiseTopItems 
    WHERE (GRNDate BETWEEN '' AND GETDATE()) 
    GROUP BY Location, LocationID ORDER BY 'Total Revenue' desc 
 )

答案 2 :(得分:0)

假设您按查询获得前5名记录

select Top 5 * 
from Table_name 
order by Location desc

所以要获得95条记录

select Top 100 * 
from Table_name 
order by Location desc
except
select Top 5 * 
from Table_name 
order by Location desc

答案 3 :(得分:0)

在第一个CTE中选择全部,在第二个CTE中选择前5个,然后使用EXCEPT

WITH CTE_ALL AS 
(
    SELECT 
            Location ,
            SUM(SellingPrice) AS [Total Revenue] ,
            LocationID
    FROM    BI_LocWiseTopItems
    WHERE   ( GRNDate BETWEEN '' AND GETDATE() )
    GROUP BY Location ,
            LocationID
)
, CTE_TOP5 AS 
(
    SELECT TOP 5 * FROM CTE_ALL 
    ORDER BY [Total Revenue]
)
SELECT * FROM CTE_ALL
EXCEPT
SELECT * FROM CTE_TOP5

SQLFiddle DEMO - 针对CTE简化

答案 4 :(得分:0)

; WITH top5 AS (
  SELECT TOP 5
         Location
       , TotalRevenue
       , LocationID
  FROM   your_table
  ORDER
      BY TotalRevenue DESC
)
SELECT Location
     , TotalRevenue
     , LocationID
FROM   your_table
EXCEPT
SELECT Location
     , TotalRevenue
     , LocationID
FROM   top5