Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Bases de datos > Firebird e Interbase
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 19-08-2008
lbuelvas lbuelvas is offline
Miembro
 
Registrado: may 2003
Ubicación: Colombia
Posts: 378
Poder: 22
lbuelvas Va por buen camino
El problema que se te presenta egostar es que no puedes utilizar la clausula order by en uniones, el order lo puedes colocar al final de la union para indicar el orden del resultado final.

Lo mejor es utilizar un procedimiento almacenado, si alguien encuentra una forma mejor por favor nos dice.

Miremos el ejemplo:

Código SQL [-]
CREATE TABLE FACTURAS (
    ID_FACTURA   INTEGER NOT NULL,
    ID_CLIENTE   INTEGER NOT NULL,
    FECHA        DATE NOT NULL,
    VALOR_TOTAL  NUMERIC(15,2) NOT NULL
);


/* Primary Keys  */


ALTER TABLE FACTURAS ADD CONSTRAINT PK_FACTURAS PRIMARY KEY (ID_FACTURA);


/* Indices */

CREATE INDEX IDX_FACTURAS_FECHA ON FACTURAS (FECHA);

/* Datos */
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (1, 1, '2008-01-01', 50000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (2, 1, '2008-01-01', 100000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (3, 1, '2008-02-01', 20000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (4, 2, '2008-02-01', 40000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (5, 3, '2008-02-01', 80000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (6, 4, '2008-02-01', 90000);
INSERT INTO FACTURAS (ID_FACTURA, ID_CLIENTE, FECHA, VALOR_TOTAL) VALUES (7, 2, '2008-03-01', 120000);

Supongamos por ejemplo que queremos saber la primera y la ultima factura entre dos fechas, este procedimiento lo puede hacer:

Código SQL [-]
SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_FACTURAS (
    fecha_inicial date,
    fecha_final date)
returns (
    id_factura integer,
    fecha date,
    valor_total numeric(15,2))
as
begin
  -- Procedimiento para saber la primera y la ultima factura
  -- en un rango de fechas

  -- Busca la primera factura
  select first 1 id_factura,
                 fecha,
                 valor_total
  from  facturas
  where fecha between :fecha_inicial and :fecha_final
  order by id_factura
  into :id_factura,
       :fecha,
       :valor_total;
  if (id_factura is not null) then
    suspend;

  -- Busca la ultima factura
  select first 1 id_factura,
                 fecha,
                 valor_total
  from  facturas
  where fecha between :fecha_inicial and :fecha_final
  order by id_factura desc
  into :id_factura,
       :fecha,
       :valor_total;
  if (id_factura is not null) then
    suspend;
end^

SET TERM ; ^

GRANT SELECT ON FACTURAS TO PROCEDURE SP_FACTURAS;

GRANT EXECUTE ON PROCEDURE SP_FACTURAS TO SYSDBA;

El if (id_factura is not null) es para evitar que te salgan registros nulos cuando no hay facturas en el ranog de fechas.

Ejecuta el procedimiento con estos casos, correlos uno por uno

Código SQL [-]
select * from SP_FACTURAS('01/01/2008', '01/01/2008');
select * from SP_FACTURAS('01/01/2008', '01/04/2008');
select * from SP_FACTURAS('01/04/2008', '01/04/2008');

Espero que les sea de utilidad.
__________________
Luis Fernando Buelvas T.
Responder Con Cita
  #2  
Antiguo 19-08-2008
Jose Roman Jose Roman is offline
Miembro
 
Registrado: jul 2006
Ubicación: Colombia
Posts: 361
Poder: 18
Jose Roman Va por buen camino
Smile

Ok, viendo todo lo anterior en definitava solamente se resuelve mediante un procedimiento almacenado, gracias a todos por ayudarme
Responder Con Cita
  #3  
Antiguo 19-08-2008
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Gracias Luis Fernando, ya se me ha aclarado que el problema está en el order by y de hecho, ya sabiendo eso, veo que es cosa del sql estandard que no permite eso en una unión.

Nuevamente, gracias.

// Saludos
Responder Con Cita
  #4  
Antiguo 19-08-2008
lbuelvas lbuelvas is offline
Miembro
 
Registrado: may 2003
Ubicación: Colombia
Posts: 378
Poder: 22
lbuelvas Va por buen camino
Encantado de poderles servir.
__________________
Luis Fernando Buelvas T.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
obtener el primer registro de una consulta + el ultimo de otra Gaim2205 SQL 9 16-06-2008 23:31:20
Seleccionar ultimo item de un listbox gallipi OOP 5 28-11-2007 00:29:38
Seleccionar el ultimo registro de un campo juangabriel1786 MySQL 2 25-08-2007 04:35:32
Primer Registro alcides Varios 5 04-05-2005 17:34:37
Ultimo registro ander Firebird e Interbase 3 18-03-2004 14:52:02


La franja horaria es GMT +2. Ahora son las 18:39:35.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi