Join with max time in EF Core C# - c#

SELECT *
FROM Jobs j
WHERE j.InsertTime = (SELECT MAX(InsertTime) FROM Jobs)
How convert this SQL script to C# query?
I try this but not worked:
from j in _dbContext.Jobs
group j by j.InsertTime into g
select g.OrderByDescending(s=>s.InsertTime).First() into item
select item;
Sample data:
title | insertTime
------|-------------
AA | 2022-05-03
B | 2022-05-03
A | 2022-05-04
B | 2022-05-04
Result:
title | insertTime
------|-------------
A | 2022-05-04
B | 2022-05-04

Use the following query:
var query =
from d in _dbContext.Jobs.Select(d => new { d.Title }).Distinct()
from j in _dbContext.Jobs
.Wehere(j => j.Ttle == d.Ttle)
.OrderByDescending(j => j.InsertTime)
.Take(1)
select j;

Related

how to group data in Linq with date

Im using Linq and having 2 tables which store the record as following
OrderMasterTable
Order_ID |Place_Date |ExpectedDelivery_Date |IsDelivered
==========|=============|=======================|============
1 |1993-02-19 | 1993-02-20 00:01:00 | True
2 |1993-02-20 | 1993-02-20 00:01:00 | True
3 |1993-02-21 | 1993-02-22 00:01:00 | True
4 |1993-02-22 | 1993-02-23 00:01:00 | False
OrderAssignTable
Order_ID |Delivered_By |Delivery_Date
==========|=============|=======================
1 |User123 | 1993-02-20 00:01:00
2 |UserXyz | 1993-02-20 00:01:01
3 |User345 | 1993-02-24 00:01:00
I want to group output data by delivered date in such a way that it appears in a following way:
Date: 1993-02-20,
OnTime: 1,
Delayed:1
Date: 1993-02-22,
OnTime :1,
Delayed: 0
* OnTime if deliveryDateTime is <= ExpectedTime
* Date is deliveryDate
pls,help me out
you can try this.
var query = from assign in OrderAssignTable
join master in OrderMasterTable on assign.Order_ID equals master.Order_ID
where master.IsDelivered == true
group new { assign, master } by assign.Delivery_Date.Date into g
select new
{
Date = g.Key,
OnTime = g.Count(i => i.assign.Delivery_Date <= i.master.ExpectedDelivery_Date),
Delayed = g.Count(i => i.assign.Delivery_Date > i.master.ExpectedDelivery_Date)
};
That should do:
var result = Orders
.Join(Assigns, o => o.OrderId, a => a.OrderId, (o, a) => new {Order = o, Assign = a})
.GroupBy(o => o.Order.ExpectedDeliveryDate.Date)
.Select(g => new
{
Date = g.Key,
OnTime = g.Count(o => o.Assign.DeliveryDate <= o.Order.ExpectedDeliveryDate),
Delayed = g.Count(o => o.Assign.DeliveryDate > o.Order.ExpectedDeliveryDate)
})
.ToArray();

I need to query table for values in two duplicate columns

I'm working in ASP.NET Core. I have a problem with querying rows which have same User_id and Definition_id, if there are any like that, I need ID of the row.
+----+---------+---------------+
| Id | User-id | Definition-id |
+----+---------+---------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
| 4 | 3 | 1 |
| 5 | 4 | 1 |
| 6 | 4 | 1 |
| 7 | 5 | 2 |
| 8 | 6 | 1 |
+----+---------+---------------+
I need to query table like this, to return { 5, 6 } to me, because of them having same user AND definition ids.
I've tried Groupby for both values, but I can't get the IQueryable or IGrouping to give me the id of specific row.
I'd imagine it to work like that, but it ain't.
var placementsWithDuplicates =
from p in _context.Placements
group p by new { p.User_id, p.Definition_id } into what
select new
{
Id = what.Id,
User = what.User_id,
Defi = what.Definition_id,
};
foreach (var p in placementsWithDuplicates)
{
issues.Add(new IssueModel()
{
Type = "Praxe ID[" + p.Id + "]",
Name = "User id [" + p.User + "], Definition id [" + p.Defi + "]",
Detail = "So user shouldnt have data for more definitons!"
});
};
Thanks to Satish Hirpara for best answer, it needed a little update so I post the thing that ended up working well:
var B = from p in _context.Placements
group p by new { p.User_id, p.Definition_id } into what
where what.Count() > 1
select new
{
User_id = what.Key.User_id,
Definition_id = what.Key.Definition_id
};
var placementsWithDuplicates = from A in _context.Placements
join b in B on new { A.User_id, A.Definition_id } equals new { b.User_id, b.Definition_id }
select A;
Please find below SQL query:
SELECT A.*
FROM Placements A
INNER JOIN
(SELECT User_id, Definition_id FROM Placements
GROUP BY User_Id, Definition_id
HAVING COUNT(*) > 1) B
ON A.User_id = B.User_id AND A.Defination_id =
B.Defination_id
You can create a temp table to avoid join of sub query.
If you want linq query then I tried to create it from above query, please find it below:
--- sub query
var B = from p in Placements
group p by new { p.User_id, p.Definition_id } into what
where what.count() > 1
select new
{ User_id = what.User_id,
Definition_id =what.Definition_id
};
--- join
Var result = from A in Placements
Join B ON A.User_id = B.User_id
AND A.Defination_id = B.Defination_id
Select A
Please try this one.
Try This
var placementsWithDuplicates = from p in _context.Placements.Where(m => m.User_id == m.Definition_id)
select new {
Id = p.Id,
User = p.User_id,
Defi = p.Definition_id,
};
// this is same as the top one
var placementsWithDuplicates = from p in _context.Placements where p.User_id == p.Definition_id
select new {
Id = p.Id,
User = p.User_id,
Defi = p.Definition_id,
};
foreach (var p in placementsWithDuplicates)
{
issues.Add(new IssueModel()
{
Type = "Praxe ID[" + p.Id + "]",
Name = "User id [" + p.User + "], Definition id [" + p.Defi + "]",
Detail = "So user shouldnt have data for more definitons!"
});
};

LINQ to SQL - Count number of certain item types in each order

For the sake of simplicity of this post, suppose I have data in an Orders table as follows. Here the CustomerId is a foreign key to Customers table. Question: How can we write a LINQ Query to find the count of vegetables (V) and the fruits (F) each customer ordered?
Orders Table:
OrderId | CustomerId | OrderType
1 | 11 | V
2 | 11 | V
3 | 11 | F
4 | 11 | V
5 | 12 | V
6 | 15 | F
7 | 15 | V
8 | 15 | F
I can count the number of orders for each customer as follows. But how about number of Vegetables and number of Fruits in each order?:
var Query1 = from o in Orders
group o by o.CustomerId
into grp
select new {CustomerId = grp.Key, OrderCount = grp.Count()};
You can to use a subquery:
var Query1 = from o in Orders
group o by o.CustomerId into grp
select new {
CustomerId = grp.Key,
OrderCount = grp.Count(),
OrderCounts = from g in grp
group g by g.OrderType into grp2
select new { OrderType = grp2.Key, Count = grp2.Count() }
};
or you can group by both CustomerId and OrderType:
var Query1 = from o in Orders
group o by new { o.CustomerId, o.OrderType } into grp
select new {
CustomerId = grp.Key.CustomerId,
OrderType = grp.Key.OrderType,
OrderCount = grp.Count()
};
They will both return the same data but in slightly different form.

How to find the min dates from the list of items?

I have a table structure like this
id | itemId | date |
1 | a1 | 6/14/2015
2 | a1 | 3/14/2015
3 | a1 | 2/14/2015
4 | b1 | 6/14/2015
5 | c1 | 6/14/2015
From this table structure I am trying to get all the distinct items that has min date. for e.g. I am trying to get id = 3,4 and 5.
I have tried following code but I couldn't
var items = (from i in _db.Items
//where min(i.date) // doesn't seem right
group i by i.itemID
into d select new
{
iId = d.Key,
}).Distinct();
Given your sample data, I would do this:
var query =
from i in _db.Items
group i by i.itemId into gis
let lookup = gis.ToLookup(x => x.date, x => x.id)
from x in lookup[gis.Min(y => y.date)]
select x;
var items = from i in _db.Items
group i.date by i.itemID
into d select new {
iId = d.Key, iDate = d.Min()
};

C# Group with conditional

how can i grouping a data with conditional if bill < 10 ?
i have table:
meetingId | bill
------------------
a | 6
b | 7
c | 1
a | 5
a | 3
b | 4
g | 2
expected results :
a = 6+5+3 = 14 limit is 10 --> 10 and 4
b = 7+4 = 11 so limit is 10 --> 10 and 1
c and g not over the limit.
meetingId | bill
------------------
a | 10
a | 4
b | 10
b | 1
c | 1
g | 2
i tried in SQL why but i stuck with if condition
my SQL :
SELECT NO_ORDRE
,ORDRE.CODE_CLIENT As CodeCl
,[CODE_DEST]
,ORDRE.RS_NOM As OrdreRS
,ORDRE.ADRESSE As OrdreAdr
,ORDRE.CP As OrdreCP
,ORDRE.VILLE As OrdreVille
,ENLEV_CREMB
,ENLEV_DECL
,MODAL_MODE
,[PAYS]
,[INSEE]
,[SIRET]
,ORDRE.TEL As OrdreTel
,ORDRE.FAX As OrdreFax
,[EMAIL]
,[NBR_COLIS]
,[POID]
,[OBS]
,[DATE_CREE]
,[DATE_MODIF]
,[REF_EXPED]
,[AUTRE_REF]
,[AGENCE]
,[TRANSPORTEUR]
,NOM
,CAPITAL
,LIBELLE
,T_LOGO.IMG As FaImg
,T_LOGO.ADRESSE As FaAdr
,T_LOGO.CP As FaCp
,T_LOGO.VILLE As FaVille
,T_LOGO.TEL As FaTel
,T_LOGO.FAX As FaFax
,FAWEB_CLIENT.RS_NOM As CliRsNom
,FAWEB_CLIENT.ADRESSE As CliAdr
,FAWEB_CLIENT.CP As CliCp
,FAWEB_CLIENT.VILLE As CliVille
FROM [ORDRE]
LEFT JOIN T_LOGO ON ORDRE.TRANSPORTEUR = T_LOGO.NOID
LEFT JOIN FAWEB_CLIENT ON ORDRE.CODE_CLIENT = FAWEB_CLIENT.CODE_CLIENT
WHERE (STATUT_ORDRE = 2) AND (TRANSPORTEUR IN (SELECT ParsedString From dbo.ParseStringList(#Trans)))
and then i use in C#
List<Pers_Ordre> oListOrdre = new List<Pers_Ordre>();
while (readerOne.Read())
{
Pers_Ordre oPerOrdr = new Pers_Ordre();
Pers_Ordre test = (from t in oListOrdre where t.DestId == readerOne["CODE_DEST"].ToString() select t).FirstOrDefault();
oPerOrdr.OrdreId = Convert.ToInt32(readerOne["NO_ORDRE"]);
oPerOrdr.DestId = readerOne["CODE_DEST"].ToString();
if (test == null)
{
oListOrdre.Add(oPerOrdr);
}
else
{
int NbrColis = (from t in oListOrdre where t.DestId == readerOne["CODE_DEST"].ToString() select t.NbrColis).FirstOrDefault();
if (NbrColis < 5)
{
test.NbrColis += NbrColis;
}
}
}
it not work what i expected.
Thanks for your help!
(Not really an answer, but this doesn't fit in a comment.)
Here's a LINQ-to-Objects query that groups items by meetingId and creates new items such that there is one item with bill less than 10 and as many items as needed with bill equalling 10 to keep the sum:
Is this what you're looking for?
Code:
var list = new List<Tuple<char, int>>
{
Tuple.Create('a', 6),
Tuple.Create('b', 7),
Tuple.Create('c', 1),
Tuple.Create('a', 5),
Tuple.Create('a', 3),
Tuple.Create('b', 4),
Tuple.Create('g', 2),
};
var result = list
.GroupBy(x => x.Item1)
.Select(g => new
{
Key = g.Key,
Sum = g.Sum(x => x.Item2)
})
.Select(p => new
{
Key = p.Key,
Items = Enumerable.Repeat(10, p.Sum / 10)
.Concat(Enumerable.Repeat(p.Sum % 10, 1))
})
.SelectMany(p => p.Items.Select(i => Tuple.Create(p.Key, i)))
.ToList();
This SQL query will return the wanted results:
SELECT meetingId, SUM(bill) as bill_total
FROM table
GROUP BY meetingId
HAVING SUM(bill) < 10
You should not do this at the client side because it can get pretty intensive, a simple GROUP BY with a HAVING clause should give you the expected results:
Sample data:
The query you need:
SELECT
MeetingID,
SUM(bill) AS Total
FROM
Table_1
GROUP BY
MeetingID
HAVING
SUM(bill) < 10
The results of the query:
table.GroupBy(p => p.meetingId).Where(p => p.Sum(q => q.bill) < 10)
.Select(p => new
{
meetingId= p.Key,
bill= p.Sum(q => q.bill)
});

Categories

Resources