sql到linq扩展方法(带聚合函数)

yyhrrdl8  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(503)

首先我要感谢那些花时间帮助我的人。在这个例子中,假设我的数据库中有以下表格。

  1. ------------
  2. tPerson
  3. ____________
  4. ID | AGE | countryID
  5. ------------
  6. tPet
  7. ____________
  8. ID | personID
  9. -----------
  10. tCountry
  11. ___________
  12. ID | Name

我想知道如何使用linq编写下一个查询(但是使用扩展方法)

  1. SELECT tCountry.ID, tCountryName,
  2. SUM(CASE WHEN(tPeople.Age <20 && subQ.hasPets = 0) THEN 1 ELSE 0) AS first,
  3. SUM(CASE WHEN(tPeople IN (20,21,22,23,24,25) && subQ.hasPets > 0) THEN 1 ELSE 0) AS second,
  4. SUM(CASE WHEN(tPeople.Age > 25) THEN 1 ELSE 0) AS third
  5. FROM tPeople
  6. LEFT JOIN (
  7. SELECT tPeople.ID, COUNT(tPet.ID) AS hasPets
  8. FROM tPeople INNER JOIN tPet ON tPet.PersonID = tPeople.ID
  9. GROUPBY tPeopleID
  10. ) AS subQ
  11. ON subQ.ID = tPeople.ID
  12. LEFT JOIN tCountry ON tPeople.countryID = tCountry.ID WHERE tCountry.ID = XX
  13. GROUP BY (tCountry.ID, tCountryName)

提前谢谢!

nhjlsmyf

nhjlsmyf1#

  1. var subQuery = from tPeople in People
  2. join tPet in Pet on tPeople.Id equals tPet.PersonId
  3. group tPeople by tPeople.Id into g
  4. select new { Id = g.Key, hasPets = g.Count() };
  5. var mainQuery = from tPeopel in People
  6. join _subQ in subQuery on tPeopel.Id equals _subQ.Id into _subQLeft
  7. from subQ in _subQLeft.DefaultIfEmpty()
  8. join _tCuntry in Country on tPeopel.CountryId equals _tCuntry.Id into _tCountryLeft
  9. from tCountry in _tCountryLeft.DefaultIfEmpty()
  10. select new
  11. {
  12. Id = tPeopel.Id,
  13. Age = tPeopel.Age,
  14. HasPets= subQ.hasPets,
  15. CountryId = tCountry.Id,
  16. CountryName = tCountry.Name
  17. };
  18. var Finalquery = from mainQ in mainQuery
  19. where mainQ.CountryId == 55
  20. group mainQ by new { mainQ.CountryId, mainQ.CountryName } into g
  21. select new
  22. {
  23. CountryId = g.Key.CountryId,
  24. CountyName = g.Key.CountryName,
  25. First = g.Sum(t => (t.Age < 20 && t.HasPets == 1) ? 1 : 0),
  26. Second = g.Sum(t => (new int[] { 20, 21, 23, 24, 25 }.Contains(t.Id) && t.HasPets > 0) ? 1 : 0),
  27. Third = g.Sum(t => t.Age > 25 ? 1 : 0)
  28. };
  29. var result = await Finalquery.ToListAsync();

为了便于阅读和理解,我把它们分开了
但如果你问我,我建议你用 Raw SQL Query 或者 Dapper 在这种情况下
因为在我看来,它简单、更优化、更快
而且,据我所知,当linq查询(to sql)很复杂时,它不会生成最佳的sql查询
如果你想用 Window Functions() 以及 Sql.Ext. ,我觉得这种情况下它不是很有用,但是如果你想,首先请改变你的想法 SQL Query 使用 window function() 在里面

展开查看全部

相关问题