Results 1 to 4 of 4

Thread: MS SQL Top Problem

  1. #1
    Join Date
    Aug 2006
    Posts
    2

    MS SQL Top Problem

    Hi, i want to make a query to get 5 news of 8 ignoring the first 3, i've made this code but the problem is when i have less than 3 news, TOP N becomes negative, can you help me?

    Thanks in advance

    SELECT * ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM (SELECT TOP
    (SELECT COUNT(ID) - 3 AS Expr1
    FROM Clube AS Clube_2) ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM (SELECT TOP (8) ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM Clube AS Clube_1
    ORDER BY ID DESC) AS Expr2
    ORDER BY ID) AS Expr3
    ORDER BY ID DESC

  2. #2
    Join Date
    Sep 2005
    Posts
    168
    --if your query is executed the expected way,
    --the following might work:

    SELECT * ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM (SELECT TOP
    (SELECT CASE WHEN COUNT(ID) - 3 <= 0 THEN COUNT(ID) ELSE COUNT(ID) - 3 END AS Expr1
    FROM Clube AS Clube_2) ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM (SELECT TOP (8) ID, Titulo, Breve, Artigo, Data, Autor, Foto, Categoria
    FROM Clube AS Clube_1
    ORDER BY ID DESC) AS Expr2
    ORDER BY ID) AS Expr3
    ORDER BY ID DESC

    --HTH--

  3. #3
    Join Date
    Sep 2002
    Posts
    5,938
    Try with case clause to test count(id), specify a number when count(id) is less than 3.

  4. #4
    Join Date
    Aug 2006
    Posts
    2
    Thanks, it worked.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •