日期:2014-05-20 浏览次数:20823 次
//假设你的表名为table,与之关联的店铺表名为shop //如下语句经过测试通过 var tmp = from p in db.table group p by p.shopid into g select new { g.Key, count = g.Count(), name = g.Select(q=>q.shop.name).First() };
------解决方案--------------------
create database TestDb use TestDb create table shop( [id] int identity primary key, [name] nvarchar(20) ) create table buy( [id] int identity primary key, [time] nvarchar(20), [cash] int, [shopid] int foreign key references shop(id) ) insert into shop values('门店1') insert into shop values('门店2') insert into shop values('门店3') insert into shop values('门店4') insert into shop values('门店5') insert into buy values('2010-10-1 12:22:43',20,1) insert into buy values('2010-10-1 12:22:43',20,1) insert into buy values('2010-10-1 12:22:43',20,2) insert into buy values('2010-10-1 12:22:43',20,3) insert into buy values('2010-10-1 12:22:43',20,4) insert into buy values('2010-10-2 12:22:43',20,1) insert into buy values('2010-10-2 12:22:43',20,1) insert into buy values('2010-10-2 12:22:43',20,3) insert into buy values('2010-10-4 12:22:43',20,1)
------解决方案--------------------
我觉得6楼的LINQ语句还有优化的空间: protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { DataClassesDataContext db = new DataClassesDataContext(); GridView1.DataSource = from p in db.buy group p by new { p.shopid, time = SqlMethods.DateDiffDay(Convert.ToDateTime(p.time), new DateTime(1900, 1, 1)) } into g orderby g.Key.time select new { time=g.Key.time, name = g.FirstOrDefault(q => q.shop.name), count = g.Count() }; GridView1.DataBind(); } }