Ficou tão interessante o post que eu modelei as tabelas para testar, com valores inteiros por preguiça:
CREATE TABLE alugueis (
id int(11) NULL,
id_filme int(11) NULL,
valor_aluguel int(11) NULL,
data_aluguel datetime NULL,
PRIMARY KEY(id)
)
ALTER TABLE `alugueis`
ADD CONSTRAINT `fk_id_filmes`
FOREIGN KEY(`id_filme`)
REFERENCES `filmes`(`id`)
INSERT INTO alugueis(id, id_filme, valor_aluguel, data_aluguel)
VALUES(1, 1, 2, '2008-09-10 5:29:57.0')
GO
INSERT INTO alugueis(id, id_filme, valor_aluguel, data_aluguel)
VALUES(2, 1, 1, '2008-09-13 5:29:57.0')
GO
INSERT INTO alugueis(id, id_filme, valor_aluguel, data_aluguel)
VALUES(3, 1, 1, '2008-09-16 5:29:57.0')
GO
INSERT INTO alugueis(id, id_filme, valor_aluguel, data_aluguel)
VALUES(4, 1, 1, '2008-09-18 5:29:57.0')
GO
INSERT INTO alugueis(id, id_filme, valor_aluguel, data_aluguel)
VALUES(5, 1, 1, '2008-09-20 5:29:57.0')
GO
CREATE TABLE filmes (
id int(11) NOT NULL DEFAULT '0',
custo int(11) NOT NULL,
PRIMARY KEY(id)
)
INSERT INTO filmes(id, custo)
VALUES(1, 4)
GO
Reparem que no primeiro aluguel o valor de aluguel foi 2 (era lançamento). Depois todos alugueis foram a 1 real.
Então, a data que o filme começou a dar lucro foi em 2008-09-16…
oyama:
Teste esta outra solução (testei no Oracle):
select f.id, sum(a.valor_aluguel), f.custo, max(a.data_aluguel)
from filme f, aluguel a
where a.id_filme = f.id
group by f.id, f.custo
having sum(a.valor_aluguel) >= f.custo
Testei aqui e retorna o valor da data máxima… não funcionou.
o mesmo com
schistossoma:
Buenas!
Tenta algo mais ou menos assim.
select case when sum(Alugueis.Valor_Aluguel) >= Filmes.Custo then max(Alugueis.Data_Aluguel)
else 0 end, Alugueis.ID_Filme
from Alugueis
join Filmes on Filmes.ID = Alugueis.ID_Filme
group by Alugueis.ID_Filme, Alugueis.Valor_Aluguel
Não cheguei a testar aqui com essa modelagem de filmes e alugueis. Mas com uma estrutura mais ou menos parecida com essa deu certo. Se não rolar, fica mais simples deixar pra resolver no código mesmo. :)
Estou decidido a mandar para meu professor de BD da facul e tirar o sono dele :twisted: .