So, I've been trying to replicate this SQL
query:
select COUNT(*) as Total_2_Review
from (
select processed_image_id, count(*) as Total_Confirm from dbo.history
where action_id=104
group by processed_image_id
having count(*) > 1
) as tbl
with Linq
as follows:
var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104)
group h by new { h.ActionId, h.ProcessedImageId } into g
where g.Key.ActionId > 1
select g).Count();
However, I know it should not be right because I am not selecting the actual count greater to 1 in my group clause.
How can I accomplish this SQL query as a LINQ query?
There is no direct having keyword in LINQ to do this we need to use the where clause itself. You can query the LINQ to SQL to have both Group By and Having like this.
The SELECT statement used in the GROUP BY clause can only be used contain column names, aggregate functions, constants and expressions. The HAVING clause is used to restrict the results returned by the GROUP BY clause.
Hi, How to write Linq Query for below SQL Query. Select Count (ul.OriginId),ul.OriginId from UserLink ul Where ul.OriginId is not null group by ul.OriginId having count (ul.OriginId)>1 Select ul.UserId from UserLink ul where ul.OriginId= 123 Finally I want to return UserId group by OriginId but here I have written in two separate queries.
As you can see the result retrieved by LINQ is literally the same as the one by SQL query. Now let’s move on to the next query using GROUP BY clause with a composite key.
LINQ makes no difference between Where
and Having
. An appropriate SQL query would be generated based on your placement of the Where
clause.
Here is how I would translate your SQL query to LINQ:
var total2Review = secondDb.Histories
.Where(i => i.ActionId == 104) // This "Where" remains a "where"
.GroupBy(i => i.ProcessedImageId)
.Where(g => g.Count() > 1) // This "Where" becomes "having"
.Count(); // This gets the overall count
Change Key.ActionId
for .Count()
in the where
after the group by
:
var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104)
group h by new { h.ActionId, h.ProcessedImageId } into g
where g.Count()> 1
select g).Count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With