Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group By Multiple Columns

How can I do GroupBy multiple columns in LINQ

Something similar to this in SQL:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2> 

How can I convert this to LINQ:

QuantityBreakdown (     MaterialID int,     ProductID int,     Quantity float )  INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM(Quantity) FROM @Transactions GROUP BY MaterialID, ProductID 
like image 454
Sreedhar Avatar asked May 11 '09 07:05

Sreedhar


People also ask

Can GROUP BY have multiple columns?

A GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.

Can we apply GROUP BY on multiple columns in SQL?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.

What happens when you GROUP BY multiple columns in SQL?

When the grouping criteria are defined on more than one column or expression then all the records that match and have the same values for their respective columns mentioned in the grouping criteria are grouped into a single record.

How do you group columns in SQL?

The SQL GROUP BY clause allows us to group individual data based on defined criteria. You can group individual data by one or more table columns. In order to do the grouping properly, you often need to apply aggregate functions to the column(s) within the SQL SELECT statement.


2 Answers

Use an anonymous type.

Eg

group x by new { x.Column1, x.Column2 } 
like image 127
leppie Avatar answered Sep 22 '22 17:09

leppie


Procedural sample:

.GroupBy(x => new { x.Column1, x.Column2 }) 
like image 23
Mo0gles Avatar answered Sep 20 '22 17:09

Mo0gles