1
I would like to do a sub-query today on 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 do a select in the clients table where in the stage table the last int_EP is=4 (or the variable you want)
The query below also returns similar (not done with query in 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 consultation:
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 (Id do Estagio do Processo)
That is, it should only bring the record int_ID=8718, because the int_IDC (Idclient) it has 3 records but the last EP is in 4.
What the consultation should do: Return the last client process step, that is, the client may have several, but which one is the last (TOP 1 ...order by ID DESC)
In my query he returns the 3 records. With Id=4, ok it finds, but brings all records (3) should only bring the int_ID=8718
With Id=2 it does not find result, ok correct :)
Sorry the question got big, but I wanted to show you the whole process. This question is already an update of my initial question: Lambda, Where com subconsulta
My client can go through the process stage that goes from 1 to 10, with several orders, like goes to 1, then to 7, back to 4, anyway, I need to identify in which Stage he is:
– Dorathoto
you have already tried to do in two steps, first get the data from tbl_internship and then tbl_Admin ?
– Marco Souza
No, I could give a basic example?
– Dorathoto
you can pass the design of your tables.
– Marco Souza
have tried using Sql Profile?
– Jhonathan
pass your relevant Entity.Cs files.
– Jonny Piazzi
I put my SQL print and my model shows the names of the SQL fields
– Dorathoto