首页 > 解决方案 > 类似 Linq 的 group by for sql

问题描述

似乎 sqlgroup 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

林克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 我肯定只想返回列的子集,id比如titleemail

标签: sqlsql-server

解决方案


推荐阅读