0

数据库中有一张表:

    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](150) NOT NULL,
    [date_of_birth] [date] NOT NULL,

我需要为 GridView 获取一个包含 2 列的数据源。

----------------
| age || count |
----------------
| 20  ||   3   |
| 21  ||   4   |
| 25  ||   5   |
----------------

是否可以通过一个查询来完成?

我试过的:

            var dates = (from u in db.Users
                         group u by u.date_of_birth into g
                         select new { age = calculateAge(g.Key) }).ToList();

            var dates1 = from d in dates
                         group d by d.age into g
                         select new { age = g.Key, count = g.Count() };

            GridView1.DataSource = dates1;
            GridView1.DataBind();

这行得通,但我认为有一种方法可以让它更简单。或不?

PS calculateAge 具有以下签名

private int calculateAge(DateTime date_of_birth)
4

1 回答 1

1
  • First of all you have a logic flaw in the first query. You are using grouping by date, not by age, so peoples who born in same year but on different day will be grouped into different sets. This 'group by' is superseded by 2nd query 'group by' clause.
  • 2nd thing to note is that your 2nd query will use actual results of 1st query (see ToList() call) so it will be running on .NET, not on SQL side.

Here is my vision for you query (count number of peoples with same age):

var dates = from u in db.Users
   select new { age = calculateAge(g.Key) } into ages
   group ages by ages.age into g
   select new { age = g.Key, count = g.Count() };

Or even without anonymous type declaration:

var dates = from u in db.Users
   select calculateAge(g.Key) into ages
   group ages by ages into g
   select new { age = g.Key, count = g.Count() };
于 2013-07-06T15:10:31.547 回答