如何将sql union转换为linq

时间:2010-04-30 11:40:50

标签: c# sql linq union

我使用union进行以下Transact SQL查询。 我需要一些关于LINQ中的内容的指示,即一些例子 如果有人能在linq上推荐一个关于UNIONS的好教程,那就太好了。

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

注意原始SQL是合并 2选择NOT连接它们。 我需要知道如何合并结果,即删除重复项,并根据条形码对存在重复的行数值求和。

3 个答案:

答案 0 :(得分:34)

在集合上运行的三个有用的Linq概念。给定c并设置e

Concat为您提供ce

中的所有内容
(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还为您提供了ce中的所有内容,但删除了所有重复内容:

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

除了c中不在e中的所有内容:

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

答案 1 :(得分:12)

这是一个通用联合的例子,不考虑你发布的场景:

var something =
                (from e in _repository
                 select new { e.Property1, e.Property2 }).Union(
                (from e in _repository
                 select new { e.Property1, e.Property2 }));

答案 2 :(得分:4)

101 Linq Samples - 有两个联合样本Union1Union2

这个Linq语句应该会得到与SQL相同的结果: (它对我来说是一个测试记录集)

var results = (from a in (from d in DiscountPromotions
            group d by d.BarCode into g
            select new { 
                BarCode = g.Key,
                AmountTaken = g.Sum(p => p.AmountTaken)
                }).Union(from i in ItemSaleTransactions
            group i by i.BarCode into o
            select new { 
                BarCode = o.Key,
                AmountTaken = o.Sum(i => i.AmountTaken)
                }) group a by a.BarCode into b
                select new {
                    BarCode = b.Key,
                    AmountTaken = b.Sum(c => c.AmountTaken)
                });