得到"分组" Key元素以外的数据

时间:2018-01-05 22:13:27

标签: linq

我试图从mysql sakila数据库中获得每个客户每月的费用总和。

我的SQL查询如下所示:

select first_name, last_name, MONTHNAME(payment_date) as Month, sum(amount) as FeeSum
from customer c
join payment p on c.customer_id = p.customer_id
where (payment_date between '2005-01-01' AND '2005-06-30')
group by c.customer_id, Month
order by Month desc, FeeSum desc;

我是在linqpad中做到的。

var q11 =   from c in Customer
        from p in Payment
        where c.Customer_id == p.Customer_id && ((DateTime)p.Payment_date) > DateTime.Parse("2005-01-01") && ((DateTime)p.Payment_date) < DateTime.Parse("2005-06-30")
        group new {c, p} by new {((DateTime)p.Payment_date).Month, p.Customer_id} into grp
        select new {
        Month = grp.Key.Month,
        FeeSum = grp.Sum(s => s.p.Amount),
        } into selection
        orderby selection.Month, selection.FeeSum descending
        select selection;
q11.Dump();

适用于FeeSum和月份,但我无法弄清楚如何获取客户的first_name和lasT_name

1 个答案:

答案 0 :(得分:0)

由于每个grp的成员都具有相同的Customer,因此请选择任何一个:

var q11 = from c in Customer
          from p in Payment
          where c.Customer_id == p.Customer_id && ((DateTime)p.Payment_date) > DateTime.Parse("2005-01-01") && ((DateTime)p.Payment_date) < DateTime.Parse("2005-06-30")
          group new { c, p } by new { ((DateTime)p.Payment_date).Month, p.Customer_id } into grp
          select new {
              grp.First().first_name,
              grp.First().last_name,
              Month = grp.Key.Month,
              FeeSum = grp.Sum(s => s.p.Amount),
          } into selection
          orderby selection.Month, selection.FeeSum descending
          select selection;

注意:我更喜欢使用let而不是select两次,但我相信内部是相同的事情:

var q11 = from c in Customer
          from p in Payment
          where c.Customer_id == p.Customer_id && ((DateTime)p.Payment_date) > DateTime.Parse("2005-01-01") && ((DateTime)p.Payment_date) < DateTime.Parse("2005-06-30")
          group new { c, p } by new { ((DateTime)p.Payment_date).Month, p.Customer_id } into grp
          let FeeSum = grp.Sum(s => s.p.Amount)
          orderby grp.Key.Month, FeeSum descending
          select new {
              grp.First().first_name,
              grp.First().last_name,
              Month = grp.Key.Month,
              FeeSum
          };