概念说明
定义:GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。
解释:GROUP BY我们可以先从字面上来理解,GROUP表示分组,BY后面写字段名,就表示根据哪个字段进行分组。GROUP BY必须得配合聚合函数来用,分组之后你可以计数(COUNT),求和(SUM),求平均数(AVG)等。
白话:就是在一个选定条件形成的表中,将GROUP BY的字段重复的消除,并对该分类下的其他数据进行统计运算,就是分组后的多行都变成一行。GROUP BY 是个分组的条件,分组后,没一组只能表示出一条数据,这条数据用统计条件统计该分组的数据。
代码模拟
注:这里仅仅模拟GROUP BY的一种情况(GROUP BY + sum)
using System;
using System.Collections.Generic;
namespace GroupBy模拟2
{
class Program
{
static string jishu = "奇数";
static string oushu = "偶数";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Program p = new Program();
p.main();
Console.ReadLine();
}
private void main()
{
Table[] tables = new Table[10];
for(int i = 0; i < 10; i++)
{
tables[i] = new Table();
if (i % 2 == 0)
{
tables[i].name = jishu;
}
else
{
tables[i].name = oushu;
}
}
for(int i = 0; i < 10; i++)
{
tables[i].display();
}
List<Table> tables2 = GROUP_BY(tables);
Console.WriteLine("GROUP BY 后的输出");
foreach(Table table in tables2)
{
table.display();
}
}
private List<Table> GROUP_BY(Table[] tables)
{
List<Table> tables2 = new List<Table>();
for (int i = 0; i < 10; i++)
{
string name = tables[i].name;
Table seletTb = tables2.Find(x => x.name.Equals(name));
if (null == seletTb)
{
Table tb = new Table();
tb.name = name;
tb.sum++;
tables2.Add(tb);
}
else
{
seletTb.sum++;
}
}
return tables2;
}
}
class Table
{
public string name;
public int sum;
public void display()
{
Console.WriteLine("name:" + name+ " sum:" + sum);
}
}
}
相关引用