I've been trying to translate following query from SQL to LINQ, main purpose of my query is to find two or more transactions by the same Sender in which the amount's sum is >= 2000
SELECT t.TXN_SENDER_ID,
s.SEN_FIRSTNAME,
s.SEN_LASTNAME,
SUM(t.TXN_AMOUNT)
FROM TRANSACTIONS t
INNER JOIN SENDERS s ON s.SEN_ID = t.TXN_SENDER_ID
WHERE t.TXN_DATE BETWEEN Dateadd(YEAR, -3, Getdate()) AND Getdate()
GROUP BY t.SENDER_ID, s.SENDER_NAME, s.SENDER_LASTNAME
HAVING SUM(t.TXN_AMOUNT) > 2000
Here's what I've tried:
var query = from t in context.TRANSACTIONS
join s in context.SENDERS on t.TXN_SENDER_ID equals s.SEN_ID
group new { t, s } by new { t.TXN_SENDER_ID, s.SEN_FIRSTNAME, s.SEN_LASTNAME, t.TXN_AMOUNT } into gr
where (gr.Sum(x => x.t.TXN_AMOUNT) > 1000)
select new { gr.Key.TXN_AMOUNT, gr.Key.SEN_FIRSTNAME, gr.Key.SEN_LASTNAME };
Thanks in advance
OK, you haven't answered my question, but looking at your sql query you want to filter data on TXN_DATE. My best guess:
DateTime dtFrom = DateTime.Today.AddDays(-3);
DateTime dtTo = DateTime.Today;
var query = from t in context.TRANSACTIONS
.Where(tr=>tr.TXN_DATE>=dtFrom && tr.TXN_DATE<=dtTo)
join s in context.SENDERS on t.TXN_SENDER_ID equals s.SEN_ID
group new { t, s } by new { t.TXN_SENDER_ID, s.SEN_FIRSTNAME, s.SEN_LASTNAME, t.TXN_AMOUNT } into gr
where (gr.Sum(x => x.t.TXN_AMOUNT) >= 2000)
select new
{
gr.Key.TXN_SENDER_ID,
gr.Key.SEN_FIRSTNAME,
gr.Key.SEN_LASTNAME,
gr.Sum(a=>a.TXN_AMOUNT)
};
Related
In the above diagram for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date.Value.Date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
Given above is linq query I was looking for.
Should be something close to this. I'm not around a computer to test so let me know if you get errors.
db.orders.Select(o => new { o.orderid, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.food items.Count()).Sum() * o.Quantity) + o.extraPrice) } )
Hi Could any one help how to write this below query in Linq C#
select YearValue from [Information].Year
where YearId in (select max(YearId) from curreny where BudgetCodeId = 2)
Here's what I've tried:
var maxYear =
from year in dbContext.Years
join exchange in dbContext.CurrencyExchangeRates
on year.YearId equals exchange.YearId
where exchange.BudgetCodeId == budgetCodeId
orderby year.YearValue descending
select new { yearValue = year.YearValue };
This is what you're looking for:
var maxYear = from year in dbContext.Years where (from exchange in dbContext.CurrencyExchangeRates where exchange.BudgetCodeId == 2 select exchange)
.Max(m => m.YearId) ==
year.YearId select year.YearValue;
int mYear = maxYear.First();
I am trying to convert some SQL Code to c# Linq:
SELECT Username, Count(Ticket.TicketId) as 'Tickets Completed'
FROM Ticket
INNER JOIN TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID
INNER JOIN Membership ON Ticket.CompletedBy = Membership.UserId
WHERE Ticket.ClosedDate >= #StartDate
and Ticket.ClosedDate <= #EndDate
GROUP BY Username
ORDER BY 'Tickets Completed' DESC
which displays
Paul 6
Mike 4
Donna 3
Elliot 2
I tried to use Linqer which made this more complicated and didnt return any results:
var query = from Ticket in data.Tickets
join Membership in data.Memberships on new { CompletedBy = Guid.Parse(Ticket.CompletedBy.ToString()) } equals new { CompletedBy = Membership.UserId }
where
Ticket.ClosedDate >= StartDate &&
Ticket.ClosedDate <= EndDate
group new { Membership, Ticket } by new
{
Membership.Username
} into g
orderby
"Tickets Completed" descending
select new
{
Username = g.Key.Username,
Completed = g.Count(p => p.Ticket.TicketID > 0)
};
Your help would be appreciated.
Thanks
Assuming CompletedBy and UserId columns are both uniqueidentifier in the database, you shouldn't need to do any type conversion.
var query = from t in db.ticket
join ts in db.ticketStatus
on t.TicketStatus.ID equals ts.TicketStatusID
join m in db.Membership
on t.CompletedBy equals m.UserId
where t.ClosedDate >= startDate
&& t.closedDate <= endDate
group t by m.UserName into tGroup
order by tGroup.Count(t=> t.TicketId) decending
select new {
UserName = tGroup.Key,
TicketCount = tGroup.Count()
};
I am really confused on a report I need. As of today, most of my reports were simple, so I was able to do them myself easily. But being a newbie in sql/dlinq, I cannot find my way through the following:
var closingStock =
(from p in session.Query<Product>()
select new
{
p.Id,
p.Name,
p.Batch,
p.Rate,
ClosingStock = p.Quantity - p.AllocatedQuantity,
p.DivisionId
}).ToList();
var distributedQuantityAfterPeriod =
(from i in session.Query<OutwardInvoiceItem>()
where i.ParentInvoice.Date > ToDate
select new
{
Id = i.Product.Id,
DistributedAfter = i.Quantity
}).ToList();
var distributedQuantityInPeriod =
(from i in session.Query<OutwardInvoiceItem>()
where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
select new
{
Id = i.Product.Id,
Distributed = i.Quantity
}).ToList();
var receivedQuantityAfterPeriod =
(from i in session.Query<InwardInvoiceItem>()
where i.ParentInvoice.Date > ToDate
select new
{
Id = i.Product.Id,
ReceivedAfter = i.Quantity
}).ToList();
var receivedQuantityInPeriod =
(from i in session.Query<InwardInvoiceItem>()
where i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate
select new
{
Id = i.Product.Id,
Received = i.Quantity
}).ToList();
As you can see, I am trying to build a inventory movement report for a specific date. I have the following problems:
1. How can I reduce the five queries? Is it possible?
2. How can I merge the data provided by these queries into one table which is grouped on the product id and summed on the quantity related columns? As of now, I am using for loops which are really slow.
What I am using:
C# 4, nHibernate, Sqlite
Any help will be very highly appreciated.
Regards,
Yogesh.
to reduce roundtrips use .Future() instead of .List()
let all queries return
group i by i.Id into g
select new
{
Id = g.Key,
Quantity = g.Sum(x => x.Quantity)
}).Future();
and do
var alltogether = groupedDistributedQuantityAfterPeriod
.Concat(groupedDistributedQuantityInPeriod)
.Concate(...);
from g in alltogether
group g by g.key into all
select new
{
Id = all.Key,
Quantity = all.Sum(x => x.Quantity)
};
Update:
you can reduce the number of queries with
from i in session.Query<OutwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...
from i in session.Query<InwardInvoiceItem>()
where (i.ParentInvoice.Date > ToDate) || (i.ParentInvoice.Date >= FromDate && i.ParentInvoice.Date <= ToDate)
select ...
So I have an SQL statement looks like this
SELECT T1.NAME, COUNT(T2.VALUE) AS numInstances
FROM TABLE2 T2 LEFT OUTER JOIN
TABLE1 T1 on T2.NAME_ID = T1.NAME_ID
WHERE (T2.DATE BETWEEN to_date('01-Aug-2011', 'dd-mon-yyyy')
AND to_date('31-Aug-2011' , 'dd-mon-yyyy')) AND T2.VALUE = 1))
GROUP BY T1.NAME
This statement looks for when names to match in the 2 tables and then find all '1' values (these relate to something like sick day, worked, day off, ect) in the month of august and then count how many of each I have. This SQL statement works great but I'm using MVC .NET in C# and need this to be a LINQ statement that generates a Dictionary.
So i would like the Dictionary to look something like,
NAME VALUECOUNT
John 8
Joe 1
Eric 0
I've tried
Dictionary<string,int> results =
(from t2 in db.table2.Where(t2 => m.Value == 1)
from t1 in db.table1
where(t2.DATE >= new DateTime(2011,8,1) && t2.DATE <= new DateTme(2011,8,31)
orderby t1.NAME
group new{T2, T1} by new {t2.VALUE, t1.NAME} into g
select new {
new KeyValuePair<string,int>(
g.Key.NAME,
(int)g.sum(g => g.Key.Value))
}).AsEnumerable().ToDictionary();
Ideas?
using(DbEntities db = new DbEntities())
{
var fromDate = new DateTime(2011,8,1);
var toDate = new DateTime(2011,8,31);
var dictionary =
(from t1 in db.TABLE1
join t2 in db.TABLE2.Where(x => x.VALUE == 1 && x.DATE >= fromDate && x.DATE <= toDate)
on t1.NAME_ID equals t2.NAME_ID into t2_j
from t2s in t2_j.DefaultIfEmpty()
group t2s by t1.NAME into grouped
select new { Name = grouped.Key, Count = grouped.Sum(x => x.VALUE) }).
Where(x => x.Count.HasValue).
ToDictionary(o => o.Name,o => o.Count);
return dictionary;
}