I would like to do a subquery, today in SQL:
SELECT intid as IDCliente,
(SELECT TOP (1) int_EP
FROM tbl_estagioprocesso
WHERE (int_IDC = tbl_Admin.intid)
ORDER BY int_ID DESC) AS int_EP
FROM tbl_Admin WITH (nolock)
WHERE ((SELECT TOP (1) int_EP
FROM tbl_estagioprocesso AS tbl_estagioprocesso_1
WHERE (int_IDC = tbl_Admin.intid)
ORDER BY int_ID DESC) = 4)
In case I make a select in the table clients where in the table estagioprocesso the last int_EP is = 4 (or the variable you want)
The query below also returns similar (I did not query the client table)
DECLARE @ep AS INT;
SET @ep = 4;
WITH CTE_Processos AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY [int_IDC] ORDER BY [int_ID] DESC) AS Ordem,
[int_IDC],
[int_EP]
FROM tbl_estagioprocesso
)
SELECT [int_IDC] FROM CTE_Processos WHERE Ordem = 1 AND [int_EP] = @ep;
Now how to do in Lambda or Linq?
My Model:
[Table("tbl_estagioprocesso")]
public class EstagioProcesso
{
[Key]
[Column("int_ID")]
public int EpId { get; set; }
[Column("int_IDC")]
public int ClienteId { get; set; }
[Column("int_EP")]
public byte EP { get; set; }
[Column("sdt_Data")]
public DateTime Data { get; set; }
[Column("int_IDFuncionario")]
public int IdFuncionario { get; set; }
[ForeignKey("ClienteId")]
public virtual Cliente Cliente { get; set; }
How I tried the query:
var epClientes = db.EstagioProcess
.Include(etapa => etapa.Cliente)
.GroupBy(etapa => etapa.ClienteId)
.Where(grupo => grupo
.OrderByDescending(etapa => etapa.EpId).Take(1)
.Select(etapa => etapa.EP)
.FirstOrDefault() == id);
var EP = new List<EstagioProcesso>();
foreach (var epCliente in epClientes)
{
EP.AddRange(epCliente);
}
Data from my SQL
Where:
int_ID(autonumeravel)int_IDC(ClienteId)int_EP(IddoEstagiodoProcesso)
Thatis,itshouldonlybringtherecordint_ID=8718,asint_IDC(IdClient)ithas3recordsbutthelastEPisin4.
Whatthequeryshoulddo:Returnthelaststage_processoftheclient,ietheclientcanhaveseveral,butwhatisthelast(TOP1...orderbyIDDESC)
Inmyqueryitreturnsall3records. WithId=4,okitfinds,howeveritdoesall(3)recordsshouldonlybringtheint_ID=8718
WithId=2itdoesnotfindcorrectcorrectresult:)
Sorryforthebigquestion,butwantedtoshowthewholeprocess.Thisquestionisalreadyanupdateofmyinitialquestion: Lambda, Where with subquery