SELECT Sum(dbo.amzOrdersItem.price) as SubTotal,
Sum(dbo.amzOrdersItem.shippingPrice) as ShippingTotal,
Sum(dbo.amzOrdersItem.price) + Sum(dbo.amzOrdersItem.shippingPrice) as OrderTotal
FROM dbo.amzOrders INNER JOIN
dbo.amzOrdersItem ON dbo.amzOrders.amzOrderId = dbo.amzOrdersItem.amzOrderId
WHERE dbo.amzOrders.id = '14818'
GROUP BY dbo.amzOrders.id
The query would look like this:
var query =
from order in db.amzOrders
join item in db.amzOrdersItems on order.amzOrderId equals item.amzOrderId
where order.Id == 14818
group item by order.Id into g
select new
{
SubTotal = g.Sum(i => i.Price),
ShippingTotal = g.Sum(i => i.ShippingPrice),
OrderTotal = g.Sum(i => i.Price) + g.Sum(i => i.ShippingPrice),
};
I'm not sure if the L2SQL query provider would be able to translate the OrderTotal line correctly for sure, hopefully it is simple enough.
maybe this (but its untested):
var result = from order in Context.amzOrders
where order.id == '14818'
from orderItems in Context.amzOrdersItem
on order.amzOrderId equals orderItems.amzOrderId
into orderItemsJoinData
let subTotal = orderItemsJoinData.Sum( item => item.price )
let shippingTotal = orderItemsJoinData.Sum( item => item.shippingPrice )
select new
{
SubTotal = subTotal ,
ShippingTotal = shippingTotal,
OrderTotal = subTotal + shippingTotal
};
Related
im trying to write equivalent of SQL query:
SELECT tax.name as tax, SUM(item.cost * item.amount) as total FROM Invoices inv
JOIN InvoiceItems item ON( item.invoice = inv.id )
JOIN Taxes tax ON( tax.id = it.tax )
WHERE inv.id = 1
GROUP BY tax.id
I can't figure out how to "add" total column to the query, my code is as follows
val res = Invoices
.innerJoin(InvoiceItems, { Invoices.id }, { InvoiceItems.invoice })
.innerJoin(Taxes, { InvoiceItems.tax }, { Taxes.id })
.slice( Taxes.name.alias("tax"), InvoiceItems.cost, InvoiceItems.amount )
.select { Invoices.id eq 1 }
Is it even possible to do it this way or i have to do it later in code?
You can use TimesOp within Expression.build{} block, like this:
val total = Expression.build { Invoices.cost * Invoices.amount }
val taxAndTotal = Invoices.innerJoin(InvoiceTaxes).innerJoin(Taxes)
.slice(Taxes.name, total)
.select{ Invoices.id eq 1 }
.groupBy(Taxes.id)
.map { it[Taxes.name] to it[total] }
I did not find how can we use times like InvoiceItems.cost times InvoiceItems.amount, but you can construct your own TimesOp object like this:
val taxAlias = Taxes.alias("tax")
val itemAlias = InvoiceItems.alias("item")
val invoiceAlias = Invoices.alias("inv")
println(invoiceAlias
.innerJoin(itemAlias, { invoiceAlias[Invoices.id] }, { itemAlias[InvoiceItems.invoice] })
.innerJoin(taxAlias, { itemAlias[InvoiceItems.tax] }, { taxAlias[Taxes.id] })
.slice(
taxAlias[Taxes.name].alias("tax"),
TimesOp(
itemAlias[InvoiceItems.cost],
itemAlias[InvoiceItems.amount],
InvoiceItems.amount.columnType
).sum().alias("total"))
.select { invoiceAlias[Invoices.id] eq 1 }
.groupBy(taxAlias[Taxes.id])
.prepareSQL(QueryBuilder(false))
)
Outputs the following sql for h2 syntax:
SELECT TAX.NAME tax, SUM((ITEM.COST) * (ITEM.AMOUNT)) total FROM INVOICES inv
INNER JOIN INVOICEITEMS item ON INV.ID = ITEM.INVOICE
INNER JOIN TAXES tax ON ITEM.TAX_ID = TAX.ID
WHERE INV.ID = 1
GROUP BY TAX.ID
I have two tables.First is CompetitionUsers and Competitionpoints.
There is foreign key relationship between tables with ParticipateID.
In CompetitionPoints Table there are points different points for multiple participateID.So I want to fetch Total Points and the Rank based on total points.So if there is multiple same total points for one participateID, the rank for that participateid should be same .Its same like student Total marks and Rank from that Mark.
Here is my code.
var competitionusers = (from c in db.CompetitionUsers
group c by new { c.ParicipateId, c.CompetitionPoints.FirstOrDefault().Points }
into g orderby g.Key.Points descending select
new { Points = db.CompetitionPoints.Where
(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points),
Rank = (from o in db.CompetitionUsers
group o by o.CompetitionPoints.FirstOrDefault().Points into l
select l).Count(s => s.Key > db.CompetitionPoints.
Where(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points)) + 1,
}).Where(x => x.Points != null).OrderByDescending(x => x.Points).AsQueryable();
If I understand your data model correctly, I think you could simplify to something like this:
var result = db.CompetitionUsers
// group by total points
.GroupBy(cu => cu.CompetitionPoints.Sum(cp => cp.Points))
// order by total points descending
.OrderByDescending(g => g.Key)
// calculate rank based on position in grouped results
.SelectMany((g, i) => g.Select(cu => new { Rank = i+1, TotalPoints = g.Key, CompetitionUser = cu }));
IQueryable<CompetitionLaderMadel> competitionUsers;
competitionUsers = (from c in db.CompetitionUsers
select new CompetitionLaderMadel
{
CompetitionName = c.Competition.CompetitionName,
CompetitionId = c.CompetitionId,
Points = db.CompetitionPoints.Where(x => x.ParticiapteId == c.ParicipateId).Sum(x => x.Points),
IsFollow = db.CrowdMember.Any(x => x.Following == userid && x.UserCrowd.UserID == c.UserId && x.Status != Constants.Deleted),
}).Where(x => x.Points != null && x.UserId != null).OrderByDescending(x => x.Points);
And then Wrote this Query
var q = from s in competitionUsers
orderby s.Points descending
select new
{
CompetitionName = s.CompetitionName,
CompetitionId = s.CompetitionId,
HeadLine = s.HeadLine,
UserId = s.UserId,
Points = s.Points,
Image = s.Image,
IsFollow = s.IsFollow,
UserName = s.UserName,
Rank = (from o in competitionUsers
where o.Points > s.Points
select o).Count() + 1
};
Here is My Query
var sonuc = (from c in cd.Product
join pp in cd.Product_Picture_Mapping
on c.ID equals pp.ProductID
join pcc in cd.Picture
on pp.PictureID equals pcc.ID
select new ProductViewModel() { PicturePath = pcc.Path, ProductID = c.ID }).OrderBy(x => x.ProductID).ToList().AsEnumerable().Select((entry, index) => new ProductViewModel()
{
PicturePath = entry.PicturePath,
ProductID = entry.ProductID
}).OrderBy(x => x.ProductID).GroupBy(x => x.ProductID).Select(g => new { g, count = g.Count() })
.SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) => new { j.ProductID, j.PicturePath, rn = i }));
and OUTPUT;
PicturePath ProductID RN
samplepath1 4 1
samplepath2 5 1
samplepath3 10 1
samplepath4 10 2
samplepath5 10 3
so, i want to take one row that have same Product id by higher RN, like this.
PicturePath ProductID RN
samplepath1 4 1
samplepath2 5 1
samplepath5 10 3
How can i get like this ?
Thank you
Group by ProductID and select item with max RN from each group:
var result = from x in sonuc
group x by x.ProductID into g
select g.OrderByDescending(x => x.RN).First();
Guy's I need a Lambda expression for this sql statement.
select GalleryId, Max(Bid)
from BidModels
where GalleryId in (select GalleryId from BidModels where UserId = (UserId))
group by GalleryId
I don't see why you need the subquery, given that you can just select all Bids where UserId = userid being passed in. With that in mind:
var userid = <whatever>;
var query = from b in BidModels
where b.UserId = userid
group by b.GalleryId into g
select new {Id = g.Key, MaxBid = g.Max(x => x.Bid)};
Here is how you can do it
var galleryIds = (bidModelses.Where(b => b.UserId == [YOURPARAMETER])
.Select(b => b.GalleryId));
var query = (bidModelses.Where(bm => galleryIds.Contains(bm.GalleryId))
.GroupBy(bm => bm.GalleryId)
.Select(gbm => new {gbm.Key, MaxBid = gbm.Max(p => p.BidId)}));
This seems to be the answer thanks for the help:
from b in BidModels
let MyGallery = from a in BidModels where a.UserId == (1) select new { a.GalleryId }
where MyGallery.Any()
group b.Bid by b.GalleryId into g
select new
{ Id = g.Key,
MaxBid = g.Max()
}
I'm pretty stuck on converting this to LINQ:
SELECT
COUNT(1) AS Registrations,
YEAR(Join_date) AS Year,
MONTH(Join_date) AS Month
FROM tblForumAuthor
GROUP BY YEAR(Join_date), MONTH(Join_date)
ORDER BY Year, Month
It's just a simple report, but I can't work out how to do the group by's and counts as the select new. I've only managed this pathetic attempt:
var q = (from c in db.tblForumAuthors
select new {Year = c.Join_date.Year,
Month = c.Join_date.Month,
Registrations = });
var results = db.tblForumAuthors.GroupBy(r => new {Year = r.Join_date.Year, Month = r.Join_date.Month})
.Select(g => new {Registrations = g.Count(), g.Key.Year, g.Key.Month})
.OrderBy(r => r.Year)
.ThenBy(r => r.Month)
from c in db.tblForumAuthors
group c by new {month = t.Join_Date.Month, year = t.Join_Date.Year}
into g select new {month = g.Key.month, year = g.Key.year, count = g.Count()}
Pipped to the post.... but this should do the trick. Notice how you can group by multiple fields by using an anonymous type. The properties of the group are available through the Key property of the grouping. Not sure if this will produce Count(1), though. IIRC it will be Count(*).
from c in db.tblForumAuthors
group c by new { c.Join_date.Year, c.Join_date.Month } into g
orderby g.Year, g.Month
select new {
Registrations = g.Count(),
g.Key.Year,
g.Key.Month
};
db.tblForumAuthors
.GroupBy(c => new {c.Join_date.Month, c.Join_date.Year})
.OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month)
.Select(g => new
{
Registrations = g.Count(),
Year = g.Key.Year
Month = g.Key.Month
});
I'll bet there are better ways to do it, but here's one.
If the table had two fields defined like this:
tblForumAuthor
==========================
Join_Date date
Name nvarchar(50)
You could get a report of the number of people joining in each Month+Year combo like this:
var db = new DataClasses1DataContext();
var report =
from a in db.tblForumAuthors
group a by new {Year = a.Join_Date.Year, Month = a.Join_Date.Month}
into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
Registrations = g.Count()
};
foreach( var item in report)
{
Console.WriteLine(item.Year + " " + item.Month + " " + item.Registrations);
}
it is more like this - sorry don't have ability to test it
var results = from r in tblForumAuthorm
group r by r.Join_date into
select new { Year =r.Join_Date.Year, Month = r.join_date.month };