使用 entity framework 或 linq 显示记录

Show record using entity framework or linq

我有记录

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

查询应该是这样的:

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

你必须在 Voucher_Date 上对记录进行分组,然后根据 Voucher_Type 从每个向上过滤是 salepurchase:

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)
                 }