I am studying about queries in SQLServer and I have the following scenario:
I have a batch table that has the following fields:
Lot Table
Id INT
ProdutoID INT
Preco SMALLMONEY
Inicio DATETIME
Fim DATETIME
Product Table (Products)
Id INT
Name VARCHAR
Tipo INT
Types table
Id INT
Name VARCHAR
NOTE: And a well-summarized example table
I need to make a query that gives me the current price of the product. Ex .:
Types
Id | Name
01 | Teste
02 | Testando
Products
Id | Name | Tipo
01 | Celular | 01
02 | Câmera | 02
Lots
Id | ProdutoId | Preco | Inicio | Fim
1 | 1 | 50 | 2017-08-14 13:10:57.980 | 2017-08-16 13:10:57.980
2 | 1 | 100 | 2017-08-12 13:10:57.980 | NULL
As you can see, Lots have 2 Registries the registration with NULL is the official price of the product and the first record is a promotion that starts on the 14th and ends on the 16th. the date of publication of this question is 15/08 the current price would be 50.
How do I query to select Product name, Product type, and current price? (Considering the promotion date)
NOTE: It should also work with these logs:
Id | ProdutoId | Preco | Inicio | Fim
1 | 1 | 50 | 2017-08-14 13:10:57.980 | 2017-08-16 13:10:57.980
2 | 1 | 100 | 2017-08-12 13:10:57.980 | NULL
3 | 1 | 150 | 2017-08-17 13:10:57.980 | NULL
In this case, the value of that product will increase on the 17th.
Just to not be left blank, I'm doing the second query:
select p.Nome as 'Produto', t.Nome as 'Tipo', l.Preco, MAX(p.Inicio)
from Lote as l inner join Produtos as p on l.ProdutoId = p.Id
inner join Tipos as t on p.TipoId = t.Id
group by p.Nome, t.Nome, l.preco
But it does not work the right way obviously, thank you right away!