How to get COUNT DISTINCT in translated SQL with EF Core

前端 未结 2 1658
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 03:59

I want to have EF core translate .Select(x=>x.property).Distinct().Count() into something like

SELECT COUNT(DISTINCT property)
2条回答
  •  无人及你
    2021-01-05 04:39

    I wanted to share an idea I had for solving my issues about count distinct.

    Ultimately another way of doing count distinct in a group by function, is by having nested group by functions (assuming you can aggregate your data through).

    Here is an example of what I used, it seems to work.

    Apologes for the criptic acronims, I am using this to keep my JSON as small as can be.

    var myData = _context.ActivityItems
                            .GroupBy(a => new { ndt = EF.Property(a, "dt").Date, ntn = a.tn })
                            .Select(g => new
                            {
                                g.Key.ndt,
                                g.Key.ntn,
                                dpv = g.Sum(o => o.pv),
                                dlv = g.Sum(o => o.lv),
                                cnt = g.Count(),
                            })
                            .GroupBy(a => new { ntn = a.ntn })
                            .Select(g => new
                            {
                                g.Key.ntn,
                                sd = g.Min(o => o.ndt),
                                ld = g.Max(o => o.ndt),
                                pSum = g.Sum(o => o.dpv),
                                pMin = g.Min(o => o.dpv),
                                pMax = g.Max(o => o.dpv),
                                pAvg = g.Average(o => o.dpv),
                                lSum = g.Sum(o => o.dlv),
                                lMin = g.Min(o => o.dlv),
                                lMax = g.Max(o => o.dlv),
                                lAvg = g.Average(o => o.dlv),
                                n10s = g.Sum(o => o.cnt),
                                ndays = g.Count()
                            });
    

提交回复
热议问题