2013-07-23 153 views
1
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條記錄的記錄。請幫助我我如何選擇所有其他記錄沒有前五個記錄?

+0

你是什麼意思「沒有前5名記錄「?只有最後的95個行或第一個95? – KarelG

+1

查看http://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server – incarnate

+0

SELECT top(5)Location,SUM(SellingPrice)AS'Total Revenue',LocationID FROM BI_LocWiseTopItems WHERE(GRNDATE'和GETDATE()) GROUP BY位置,位置ID ORDER BY'總收入'desc這是我的查詢。它只返回前5個記錄。 BT我想只有所有其他記錄沒有頂部5.記錄數量動態變化 – user2220385

回答

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 
) 
+0

矯枉過正。升級到MSSQL 2011,它有一個'OFFSET'子句:) – incarnate

+0

MSSQL 2011?這是2012年。但他沒有提及版本 – Nithesh

+0

和升級SQL服務器(與所有相關費用)不是矯枉過正? – Mr47

0

假設你通過查詢

select Top 5 * 
from Table_name 
order by Location desc 

獲得前5個記錄,以便讓你的95條記錄

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

試試這個。

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

在第一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

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 
相關問題