Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query using group by and having

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?

like image 760
Luis Lavieri Avatar asked Nov 25 '15 15:11

Luis Lavieri


People also ask

How to have group by and having in LINQ?

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.

What is the difference between having and group by in SQL?

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.

How to write LINQ query for below SQL query?

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.

How is LINQ different from SQL query?

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.


2 Answers

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
like image 162
Sergey Kalinichenko Avatar answered Nov 04 '22 09:11

Sergey Kalinichenko


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();
like image 27
octavioccl Avatar answered Nov 04 '22 08:11

octavioccl