LINQ样的Group By for SQL

时间:2018-09-03 09:54:20

标签: sql sql-server

似乎sql group by是更多的聚合函数(COUNT,MAX,MIN,SUM,AVG)。

select count(Id), Country 
from Customer
where Country <> 'CountryX'
group by Country

但是我们是否有一个类似于linq的查询,我们想返回按某个列分组的所有结果,例如在linq中我会做

id | title   | category | email         
------------------------------------------
1  | tname-1 | cat1     | test@example.com
2  | tname-2 | cat1     | test1@example.com
3  | tname-3 | cat2     | TEst@example.com

linq group-by

var groupedBy = list.GroupBy(item => item.Email);

甚至进行一些比较

var groupedBy = list.GroupBy(item => item.Email, StringComparer.OrdinalIgnoreCase);

结果将类似于:

key              | items
----------------------------------------------------------------------------------------------
test@example.com | [{Id :1, Title : "tname-1", category: "cat1", email: "test@example.com" },{Id :3, Title : "tname-3", category: "cat2", email: "TEst@example.com" } ]
test1@example.com| [{Id :2, Title : "tname-2", category: "cat1", email: "test1@example.com" }]

但是对于sql来说,我肯定只想返回列的子集,例如idtitleemail

0 个答案:

没有答案