简体   繁体   中英

How to convert from PostgreSQL query to LINQ or lambda expression

I have a PostgreSQL query that I need to convert to Lamba exp or LINQ to use in my ASP.NET Core C# project. Furthermore, the name of the table is "DeliveryFinances".

This is my PostgreSQL query

SELECT t1."DriverId", t2."OrderNo", COUNT(*)
FROM public."DeliveryFinances" t1
JOIN
(
    SELECT MIN("OrderNo") AS "OrderNo", "DriverId"
    FROM public."DeliveryFinances"
    GROUP BY "DriverId"
) t2 ON t1."DriverId" = t2."DriverId"
GROUP BY t1."DriverId", t2."OrderNo"
LIMIT 25

This is the result I get after running the query in pgAdmin

| DriverId| OrderNo | count |
|----------------------------
| 123123  | REQWFA  |      3|
| 345534  | ASDCA3  |      2|
| 565534  | MCJSL1  |      1|

Is there any way that I can do this in lambda or LINQ? Please help me.

Using EF Core 5, a straight forward translation seems to work:

var qmin = from t2 in DeliveryFinances
           group t2.OrderNo by t2.DriverId into dg
           select new { OrderNo = dg.Min(), DriverId = dg.Key };

var q = from t1 in DeliveryFinances
        join t2 in qmin on t1.DriverId equals t2.DriverId
        group new { t1, t2 } by new { t1.DriverId, t2.OrderNo } into t1t2g
        select new {
            t1t2g.Key.DriverId,
            t1t2g.Key.OrderNo,
            Count = t1t2g.Count()
        };
var ans = q.Take(25);

It did not seem particularly efficient on my database, but translated pretty much directly to your SQL.

A better look at your data might provide a way to use a Group Join in the query, but it might not be translatable to SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM