使用c#在数据表中选择GROUP BY

时间:2015-06-10 11:13:36

标签: c# sql group-by

我有一个dataTable,其行如下图enter image description here

所示

我想用select在该数据表上编写groupby语句来获取输出,如下所示

enter image description here

3 个答案:

答案 0 :(得分:1)

select ApplicationName, count(*) from DataTableName
group by ApplicationName

其中DataTableName应替换为数据库中表的实际名称,ApplicationName应替换为该表中包含应用程序名称的列的名称

答案 1 :(得分:0)

这就是......

SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName

或订购和过滤(按计数存在重复和顺序)......

SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

答案 2 :(得分:0)

使用LINQ

中的C#尝试此操作
var result = from tab in dt.AsEnumerable()
             group tab by tab["ApplicationNmae"]
                 into groupDt
                 select new
                 {
                     ApplicationNmae = groupDt.Key,
                     Sum = groupDt.Sum((r) => decimal.Parse(r["Count"].ToString()))
                 };

DataTable dt1 = new DataTable();
dt1 = dt.Clone();

foreach (var item in result)
{
    DataRow newRow = dt1.NewRow();
    newRow["ApplicationNmae"] = item.ApplicationNmae;
    newRow["Count"] = item.Sum;
    dt1.Rows.Add(newRow);
}

Grid.DataSource = dt1;

参考:Group by in DataTable Column sum