代码之家  ›  专栏  ›  技术社区  ›  Umesh Patil

使用实体框架或linq显示记录

  •  0
  • Umesh Patil  · 技术社区  · 9 年前

    我有记录

    voucher_id    voucher_Date    Voucher_type     Total
    
    1              1/2/2015        sale            10000
    
    2              1/2/2015        sale            15000
    
    3              1/2/2015       purchase         5000
    
    4              25/2/2015       sale            10000
    

    如何按日期显示数据并计算为,

    Voucher_Date     Sale         Purchase
    
    1/2/2015          25000        5000
    
    25/2/2015         10000
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   xanatos    9 年前

    查询应该类似于:

    var res = from x in MyTable
              group x by x.voucher_Date into y
              select new 
              { 
                  Voucher_Date = y.Voucher_Date, 
                  Sale = y.Sum(z => z.Voucher_type == "sale" ? z.Total : 0),
                  Purchase = y.Sum(z => z.Voucher_type == "purchase" ? z.Total : 0),
              }
    

    注意,我不确定EF是否支持 Sum 我用过。

    等效的SQL查询应为:

    SELECT Voucher_Date,
           SUM(CASE WHEN Voucher_type = 'sale' THEN Total ELSE 0 END) Sale,
           SUM(CASE WHEN Voucher_type = 'purchase' THEN Total ELSE 0 END) Purchase
           FROM MyTable
           GROUP BY voucher_Date
    
        2
  •  0
  •   Ehsan Sajjad    9 年前

    您必须将记录分组 Voucher_Date 然后根据 Voucher_Type 是的 sale purchase :

    var result = from v in db.Vouchers
                 group v by v.Voucher_Date into g
                 select new
                     {
                      Date = g.Key,
                      Sale = g.Where(x=>x.Voucher_Type == "sale").Sum(y=y.Total),
                      Purchase = g.Where(x=>x.Voucher_Type == "purchase").Sum(x=>x.Total)
                     }