我有下表:
----------------------------------------------
ID|Name |City |Phone |IsWorking
----------------------------------------------
1 |Joe |New York |111-111-1111|No
----------------------------------------------
2 |Helen |LA |123-456-7890|No
----------------------------------------------
3 |Mary |Chicago |373-737-7373|Yes
----------------------------------------------
4 |Joe |New York |999-999-9999|Yes
----------------------------------------------
我需要查找匹配Name
和City
且不止一次出现的行。我这样做是通过Name
和City
对行进行分组,检查计数并获取ID
和IsWorking
列。
如何编写此LINQ查询?
以下是完成此操作的相应T-SQL:
select a.ID, a.Name, a.City, a.Phone, a.IsWorking
from tb as a
right outer join (select Name, City
from tb
group by Name, City
having count(*) > 1) as b
on a.Name = b.Name and a.City = b.City
答案 0 :(得分:0)
我对VB不大,我很害怕,但在C#中你可以这样做:
var items = new List<Item>()
{
new Item() { Id = 0, Name = "Joe", City = "New York", Phone = "111-111-1111", IsWorking = false },
new Item() { Id = 1, Name = "Helen", City = "LA", Phone = "222-222-2222", IsWorking = false },
new Item() { Id = 2, Name = "Mary", City = "Chicago", Phone = "333-333-3333", IsWorking = true },
new Item() { Id = 3, Name = "Joe", City = "New York", Phone = "444-444-4444", IsWorking = true }
};
var results = from i in items
group i by new { i.Name, i.City }
into x
select new { Key = x.Key, Values = from a in x select new { ID = a.Id, a.IsWorking }};
这提供了输出:
Key: { Name = Joe, City = New York }
Values: { ID = 0, IsWorking = false }
{ ID = 3, IsWorking = true }
Key: { Name = Helen, City = LA }
Values: { ID = 1, IsWorking = false }
Key: { Name = Mary, City = Chicago }
Values: { ID = 0, IsWorking = true }
我会稍后尝试提供VB翻译,除非其他人先到达那里!
答案 1 :(得分:0)
我想我明白了。
From d In (all.GroupBy(Function(a) New With {Key a.Name, Key a.City}) _
.Where(Function(b) b.Count > 1) _
.Select(Function(c) New With {Key c.Key.Name, Key c.Key.City}))
From a In all.Where(Function(e) e.Name = d.Name AndAlso e.City = d.City).DefaultIfEmpty
Select New With {a.ID, a.Name, a.City, a.Phone, a.IsWorking}
感谢Tim的方法。
答案 2 :(得分:0)
我相信这个查询应该适合你。
Dim query = From row In db.Customers _
Group 1 By row.ContactName, row.Phone Into Count() _
Where Count > 1 _
Join row2 In db.Customers _
On New With {ContactName, Phone} _
Equals New With {row2.ContactName, row2.Phone} _
Select row2
或者:
Dim query = From row In db.Customers _
Where (From r In db.Customers _
Group 1 By r.ContactName, r.Phone Into Count() _
Where Count > 1 _
Select ContactName, Phone) _
.Contains(New With {row.ContactName, row.Phone}) _
Select row
根据需要选择适当的字段。