Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert sql union to linq

Tags:

c#

sql

linq

union

I have the following Transact SQL query using a union. I need some pointers as to how this would look in LINQ i.e some examples wouldbe nice or if anyone can recommend a good tutorial on UNIONS in linq.

select top 10 Barcode, sum(ItemDiscountUnion.AmountTaken) from (SELECT d.Barcode,SUM(AmountTaken) AmountTaken   FROM [Aggregation].[dbo].[DiscountPromotion] d    GROUP BY d.Barcode    UNION ALL    SELECT i.Barcode,SUM(AmountTaken) AmountTaken   FROM [Aggregation].[dbo].ItemSaleTransaction i    group by i.Barcode)  ItemDiscountUnion    group by Barcode 

Note the original SQL is merging the 2 selects NOT concatenating them. I need to know how to merge the results i.e. removing duplicates and summing the rows amount value where there is duplication based on bar code.

like image 623
lowlyintern Avatar asked Apr 30 '10 11:04

lowlyintern


People also ask

How do you write a Union query in Linq?

LINQ Union operator is used for finding unique elements between two sequences (Collections). For example, suppose we have two collections A = { 1, 2, 3 }, and B = { 3, 4, 5 }. Union operator will find unique elements in both sequences. { 3 } element is available in both sequences.

What is Union in Linq?

LINQ Union is an extension method that requires two collections to combine the two collections and returns the distinct elements from both collections. LINQ Union supports only method syntax; it does not support the query syntax. The Union method presents in both the classes Queryable class and Enumerable class.

Is Linq converted to SQL?

LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the . NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution.


1 Answers

Three useful Linq concepts operating on sets. Given set c and set e:

Concat gives you everything in c or e:

(From c In db.Customers Select c.Phone).Concat( _              From c In db.Customers Select c.Fax).Concat( _              From e In db.Employees Select e.HomePhone)  (From c In db.Customers _             Select Name = c.CompanyName, Phone = c.Phone).Concat(From e In db.Employees _             Select Name = e.FirstName & " " & e.LastName, Phone = e.HomePhone) 

Union also gives you everything in c and e, but removes any duplicates:

(From c In db.Customers _         Select c.Country).Union(From e In db.Employees _         Select e.Country) 

Except gives you everything in c that is not in e:

(From c In db.Customers _              Select c.Country).Except(From e In db.Employees Select e.Country) 
like image 180
Amit Rai Sharma Avatar answered Sep 21 '22 17:09

Amit Rai Sharma