I need to convert the following complicated sql query to Linq in C#:
Select Empleador.NombreComercial as Empresa,
Vacante.Puesto as Vacante,
Vacante.Actividades,
COUNT(Vacante.CveVacante) as Visitas
from Vacante
LEFT JOIN Empleador on Empleador.CveEmpleador=Vacante.CveEmpleador
LEFT JOIN VisitaVacante on Vacante.CveVacante = VisitaVacante.CveVacante
GROUP BY Empleador.NombreComercial,Vacante.Puesto, Vacante.Actividades,
Vacante.CveVacante HAVING COUNT(*) > 1 ORDER BY Visitas DESC
For the moment I already have the following:
var Visitas = (from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
select new
{
Empresa = tEmpleador.NombreComercial,
Vacante = tvacante.Puesto,
tvacante.Actividades,
Visitas = tvacante.CveVacante
}).GroupBy( );
How can I add the COUNT(Vacante.CveVacante) as Visitas and also the
GROUP BY Empleador.NombreComercial,Vacante.Puesto, Vacante.Actividades,
Vacante.CveVacante HAVING COUNT(*) > 1 ORDER BY Visitas DESC
to my linq query? I can't find information about how to complete this. The tables are tvacante, templeador, and tvisitaVacante.
Try this:
var Visitas =(from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
group new{tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} by new {tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} into g
where g.Count()>1
select new
{
Empresa = g.Key.tEmpleador.NombreComercial,
Vacante = g.Key.tvacante.Puesto,
Actividades= g.Key.tvacante.Actividades,
Visitas = g.Count()
}).OrderByDescending(e=>e.Visitas);
If you want to do it using only linq query syntax and not merging both syntax then you could also do this:
var Visitas = from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
group new{tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} by new {tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} into g
where g.Count()>1
orderby g.Count() descending
select new
{
Empresa = g.Key.tEmpleador.NombreComercial,
Vacante = g.Key.tvacante.Puesto,
Actividades= g.Key.tvacante.Actividades,
Visitas = g.Count()
};
Related
When I run this Query in SQL I get what I want:
SELECT Auckland_Park.Formative.[Formative Name]
FROM Auckland_Park.LearningUnit
INNER JOIN Auckland_Park.Formative
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Formative.FK_LU
INNER JOIN Auckland_Park.Reference
INNER JOIN Auckland_Park.Course
ON Auckland_Park.Reference.FK_Course = Auckland_Park.Course.ID
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Reference.FK_LU
WHERE Auckland_Park.Course.Name = 'BI'
My result:
Querying SQL Build
Report Develop
Java App Develop
Andriod App Set up
SharePoint Server
But when I work with my C# app I'm using LINQ to SQL, my LINQ Query looks like this:
//LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits
join a in data.Formatives
on r.ID equals a.FK_LU
join f in data.References
on r.ID equals f.FK_LU
join g in data.Courses
on f.FK_LU equals g.ID
where g.Name == ("BI")
select new
{
formativeName = a.Formative_Name,
ID = a.ID
}
).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";
It seems the same, but I'm not getting the same result that I'm getting with the SQL Query above.
//LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits
join a in data.Formatives
on r.ID equals a.FK_LU
join f in data.References
on r.ID equals f.FK_LU
join g in data.Courses
on f.FK_LU equals g.ID
where g.Name == ("BI")
select new
{
formativeName = a.Formative_Name,
ID = a.ID
}
).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";
ANSWER:
on f.FK_LU equals g.ID
f.FK_LU
must be replaced with
f.FK_Course
I have this query
SELECT t.NomeTipo, sum(v.QtdProduto)
FROM [dbo].[Vendas] AS V
RIGHT JOIN [dbo].[Produtos] AS P ON V.IdProduto = P.IdProduto
INNER JOIN [dbo].[Tipos] AS T ON P.IdTipo = T.IdTipo
group by t.NomeTipo
order by t.NomeTipo
I have tried this
var queryTipos = from vendas in repositorioVendas.Vendas
join produtos in repositorioProduto.Produtos.DefaultIfEmpty()
on vendas.IdProduto equals produtos.IdProduto
join tipos in repositorioTipo.Tipos
on produtos.IdTipo equals tipos.IdTipo
group vendas by new { tipos.NomeTipo, vendas.QtdProduto }
into novoGrupo
select new
{
NomeTipo = novoGrupo.Key.NomeTipo,
QtdProduto = novoGrupo.Sum(x => x.QtdProduto)
};
With this query I got only two results, but when I run straight from the database I get something like this:
Bebidas 16
Bolos 14
Frios 16
Pães 21
The trick is to realize that you can rewrite your query with a left join instead of a right join by swapping the order of the first two tables and that Linq doesn't have a way to really handle right joins. Also you're grouping was wrong.
var queryTipos = from produtos in repositorioProduto.Produtos
join vendas_pj in repositorioVendas.Vendas
on vendas_pj.IdProduto equals produtos.IdProduto into joined
from vendas in joined.DefaultIfEmpty()
join tipos in repositorioTipo.Tipos
on produtos.IdTipo equals tipos.IdTipo
group vendas by tipos.NomeTipo
into novoGrupo
select new
{
NomeTipo = novoGrupo.Key,
QtdProduto = novoGrupo.Sum(x => x.QtdProduto)
};
Basically a Left join in SQL
From TableA
Left Join TableB
On TableA.ID = TableB.ID
is done in Linq like this
from a in repo.TableA
join b_pj in repo.TableB
on a.ID equals b_pj.ID into joined
from b in joined.DefaultIfEmpty()
I have a join query and i want to filter the result of this query by using distinct. I want to get only one of the shoes which has same brand, model, primary color and secondary color. How can i make this ? Here is my join query.
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
where s.Quantity > 0
orderby m.ModelName
select new
{
s.ShoeID,
m.ModelName,
m.Price,
b.BrandName,
i.ImagePath
};
I found the solution. This query does approximately what i want to do
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price};
Remove price from the output and use Distinct() like this:
var query = (from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
where s.Quantity > 0
orderby m.ModelName
select new
{
s.ShoeID,
m.ModelName,
b.BrandName,
i.ImagePath
}).Distinct();
How can i write this query in LINQ lambda expression or query syntax if required? I have been trying for a while now. The multiple joins are making it difficult. The total records on the join are over 2000 and the final result should be about 15 records
select
year([date]),
month([date]),
sum(ot.rate)
from s as s
join cs cs on cs.s_id= s.id
join ot ot on ot.id = cs.o_id
group by
year([date]),
month([date])
this is the closest I have got but will not compile. I cannot access the ot property from within the select block.
var query = from se in table_se
join cs in table_cs on se.Id equals cs.S_Id
join ot in table_ot on cs.O_Id equals ot.Id
group se by new { se.Date.Year, se.Date.Month } into grp
select new
{
grp.Key.Year,
grp.Key.Month,
grp.Sum(ot.Rate)
};
You were very close - Enumerable.Sum takes a predicate
var query = from se in table_se
join cs in table_cs on se.Id equals cs.S_Id
join ot in table_ot on cs.O_Id equals ot.Id
group ot by new { se.Date.Year, se.Date.Month } into grp
select new
{
Year = grp.Key.Year,
Month = grp.Key.Month,
Sum = grp.Sum(x => x.Rate)
};
my sql statement is
SELECT c.type,c.title,c.datereg, d.ranknum
FROM T_News AS c
INNER JOIN (
SELECT a.id, COUNT(*) AS ranknum
FROM T_News AS a
INNER JOIN T_News AS b
ON (a.type = b.type)
AND (a.datereg >= b.datereg)
GROUP BY a.id
HAVING COUNT(*) <= 3
) AS d ON (c.id = d.id)
ORDER BY c.type, d.ranknum
that i get http://rickosborne.org/blog/2008/01/sql-getting-top-n-rows-for-a-grouped-query/
for Getting TOP N rows for a grouped query
EFUnitOfWork EF = new EFUnitOfWork();
T_NewsRepository News = new T_NewsRepository();
News.UnitOfWork = EF;
var query =
from news1 in News.All()
join news2 in News.All()
on news1.type equals news2.type into resjoin
group news1 by news1.id into idgroup
where idgroup.Count() <= 3
select new { idgroup };
var x = query.ToList();
I did not get any error , but "where idgroup.Count() <= 3" did not work and i get all rows in db as result
Break it down into it's smallest components and then compose the larger query from that. Let's start with the innermost query that makes sense:
SELECT
a.id, COUNT(*) AS ranknum
FROM
T_News AS a
INNER JOIN T_News AS b ON
(a.type = b.type) AND
(a.datereg >= b.datereg)
GROUP BY
a.id
HAVING
COUNT(*) <= 3
I'd convert this to:
// Items with counts/ranknum
var ranknum =
from a in News.All()
join b in News.All() on
a.type equals b.type
where
a.datereg > b.datereg
group by a.id into g
select new { g.Key as id, g.Count() as ranknum };
// Filter the ranknum.
ranknum = ranknum.Where(rn => rn.ranknum <= 3);
Then joining that with the outer query:
SELECT
c.type,c.title,c.datereg, d.ranknum
FROM
T_News AS c
INNER JOIN (<sub-query from above>) as d ON
c.id = d.id
ORDER BY
c.type, d.ranknum
That part becomes simple, as it's just a join between two existing queries.
var query =
from c in News.All()
join rn in ranknum on c.id = rn.id
orderby c.type, rn.ranknum
select new { c.type, c.title, c.datereg, rn.ranknum };
Chances are the SQL that LINQ-to-Entities generates for this is going to look really ugly, and probably be inefficient, in which case, you might want to consider placing this logic in a stored procedure and then calling that through LINQ-to-Entities (which is generally true for more complex queries).