我使用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连接它们。 我需要知道如何合并结果,即删除重复项,并根据条形码对存在重复的行数值求和。
答案 0 :(得分:34)
在集合上运行的三个有用的Linq概念。给定c
并设置e
:
Concat为您提供c
或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还为您提供了c
和e
中的所有内容,但删除了所有重复内容:
(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 - 有两个联合样本Union1和Union2
这个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)
});