我的数据库中有这些表:
TOTAL TABLE:
total_table_id | person_id | car_id | year
----------------|-----------|-----------|------
0 | 1 | 4 | 2015
1 | 1 | 2 | 2017
2 | 2 | 0 | 2017
3 | 3 | 3 | 2017
4 | 3 | 4 | 2015
PERSON TABLE:
person_id | name | age
------------|-------|-----
0 | John | 26
1 | Anna | 41
2 | Sam | 33
3 | Tim | 33
CAR TABLE:
car_id | model | color
--------|-------|-------
0 | A | red
1 | B | blue
2 | B | white
3 | D | red
4 | C | black
在下拉列表中选择年份后我想要的是得到这样的东西:
2017:
color | age | cars_count
--------|-------|------------
red | 33 | 2
white | 41 | 1
这是我目前的查询:
from a in total
join b in person
on a.person_id equals b.person_id
join c in car
on a.car_id equals c.car_id
select new
{
color = c.color,
age = b.age,
cars_count = ? // <--------This is what I don't know how to get it
}).ToList();
任何提示?
答案 0 :(得分:1)
您应该使用group by
声明
var answer = (from total in totalTable
where total.year == 2017
join car in carTable on total.car_id equals car.car_id
join person in personTable on total.person_id equals person.person_id
group person by car.color into sub
select new
{
color = sub.Key,
age = sub.Max(x => x.age),
//or age = sub.Min(x => x.age),
//or age = sub.First().age,
count = sub.Count()
}).ToList();