从SQL中选择一些行号

时间:2015-07-13 05:19:26

标签: sql sql-server

我正在使用SQL Server management studio 2008并使用TOP从数据库中选择一些数据。

SELECT 
    TOP 3 Name, Company, ta_Content, Email, Writedate
FROM dbo.ta_CONTACT
WHERE Name in ('David', 'Filo', 'Rain', 'Cone', 'Source', 'Tailor', 'Fier', 'Venesse')
ORDER BY Writedate;

因此,通过使用TOP 3,我可以从8个给定数据中收集前3个数据。但我想要做的是从给定的8个数据中选择5-7个数据。

我可以使用ROW_NUMBER(),但我想使用TOP来使用NOT IN逻辑。但是我不知道在哪里放NOT IN逻辑来显示5-7个数据。

3 个答案:

答案 0 :(得分:2)

尝试此查询:

SELECT * FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY Writedate ASC) AS rownumber,
    Name, Company, ta_Content, Email, Writedate
    FROM dbo.ta_CONTACT
) AS t
WHERE rownumber >= 5 AND rownumber <= 7

答案 1 :(得分:0)

尝试此查询。这不是正确的方法。

select TOP 2 Name, Company, ta_Content, Email, Writedate from (
SELECT TOP 3 Name, Company, ta_Content, Email, Writedate FROM dbo.ta_CONTACT
WHERE Name in ('David', 'Filo', 'Rain', 'Cone', 'Source', 'Tailor', 'Fier', 'Venesse')
ORDER BY Writedate desc)a ORDER BY Writedate

答案 2 :(得分:0)

使用TOP(3)并过滤掉第1-4行,然后你可以获得5到7条记录

SELECT TOP (3) 
    * 
FROM
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY Writedate) Seq, 
        Name, Company, ta_Content, Email, Writedate
    FROM dbo.ta_CONTACT
    WHERE 
        -- The search criteria must be inside the inner select statement
        Name in 
        ('David', 'Filo', 'Rain', 'Cone', 'Source', 'Tailor', 'Fier', 'Venesse')
) filtered
WHERE 
    Seq >= 5 
    -- If you do not need the TOP statement just use below condition
    -- Seq BETWEEN 5 AND 7