how would i use GroupBy in this linq statement? - linq-to-sql

Morning i would like to include a group by in this linq statement, Some records i have being brought back have multiple entries so i need to group them by the productAsin. so i dont have duplicates in my table.
var query = from a in dc.aProducts
join t in dc.tProducts on a.sku equals t.sku
join lp in dc.LowestPrices on a.asin equals lp.productAsin
orderby t.title
select new GetLowestPrices
{
productAsin = lp.productAsin,
sku = t.sku,
title = t.title,
tweprice = Convert.ToString(t.twePrice),
lowprice = Convert.ToString(lp.price),
amzprice = Convert.ToString(lp.tweAmzPrice),
lastupdated = Convert.ToDateTime(lp.priceDate)
};
return query.ToList();
many thanks in advance.

Use GroupBy Extension method:
var query = from a in dc.aProducts
join t in dc.tProducts on a.sku equals t.sku
join lp in dc.LowestPrices on a.asin equals lp.productAsin
orderby t.title
select new GetLowestPrices
{
productAsin = lp.productAsin,
sku = t.sku,
title = t.title,
tweprice = Convert.ToString(t.twePrice),
lowprice = Convert.ToString(lp.price),
amzprice = Convert.ToString(lp.tweAmzPrice),
lastupdated = Convert.ToDateTime(lp.priceDate)
};
var groupedData = query.GroupBy(d => d.productAsin);
return groupedData;
After that you can access that group values and put some aggregate function on them as below:
var groupedData = query.GroupBy(d => d.productAsin).Select( data => new {
productAsin = data.Key,
LowPriceSum = data.Sum(s => Convert.ToInt32(s.price))
}).ToList();
Ref:
group clause (C# Reference)
How to Use LINQ GroupBy

Related

Laravel DB::select not return value as expected

I'm having problem to view data using db::select.
Here is my full sql statement [Tested and return value as expected on mysql]
SELECT tugasan_kontrak.*,sejarah.tkh_wujud AS tkh_wujud ,sejarah.id_tindakan AS id_tindakan
FROM tugasan_kontrak
LEFT JOIN sejarah ON(
tugasan_kontrak.id_tugasan = sejarah.id_tugasan AND
jenis_tugasan='k' AND
sejarah.id_tindakan !='99' AND
id_sejarah = (SELECT MAX(id_sejarah) FROM sejarah WHERE
tugasan_kontrak.id_tugasan = sejarah.id_tugasan AND jenis_tugasan='k')
)
WHERE pegawai_tugas='890911105098' AND id_tindakan IS NOT NULL
Result
But when I try to apply this statement using db::select, no record were view.
Here the function I use to test
public function getPenggunaTindakan($value='890911105098')
{
$kontrak = DB::select("select tugasan_kontrak.*,sejarah.tkh_wujud as tkh_wujud ,sejarah.id_tindakan as id_tindakan
from tugasan_kontrak left join sejarah on(tugasan_kontrak.id_tugasan = sejarah.id_tugasan and jenis_tugasan='k' and sejarah.id_tindakan !='99' and
id_sejarah = (select max(id_sejarah) from sejarah where tugasan_kontrak.id_tugasan = sejarah.id_tugasan and jenis_tugasan='k'))
where pegawai_tugas=:nokp and id_tindakan is not null ",['nokp' => $value]);
dd($kontrak);
}
What did I do wrong?
Try the following :
DB::select(DB::raw("select tugasan_kontrak.*,sejarah.tkh_wujud as tkh_wujud ,sejarah.id_tindakan as id_tindakan
from tugasan_kontrak left join sejarah on(tugasan_kontrak.id_tugasan = sejarah.id_tugasan and jenis_tugasan='k' and sejarah.id_tindakan !='99' and
id_sejarah = (select max(id_sejarah) from sejarah where tugasan_kontrak.id_tugasan = sejarah.id_tugasan and jenis_tugasan='k'))
where pegawai_tugas=:nokp and id_tindakan is not null "),['nokp' => $value]);
If you want to inject sql query, you have to use DB::raw in laravel

MySQL: Query with SUM(if ..)

Please, help me with query:
SELECT
N.site_name,
Count(N.site_name),
SUM (IF((SC.type_conn = 'GET') && (SC.type_conn = 'CONNECT'),N.size_site,0)) as Traffic_IN,
SUM (IF(SC.type_conn = 'POST',N.size_site,0)) as Traffic_OUT
From
news N,
status_conn SC,
users U
where
N.id_conn = SC.id_conn and
N.id_user = U.id_user and
U.name_user = 'max' and
N.date_conn = '2015-08-04'
Group by
N.site_name
Order by
SUM (IF((SC.type_conn = 'GET') && (SC.type_conn = 'CONNECT'),N.size_site,0))
I don't know witch is the problem; in any case you could try this:
Select N.site_name,
Count(N.site_name),
SUM (IF((SC.type_conn = 'GET') && (SC.type_conn = 'CONNECT'),N.size_site,0)) as Traffic_IN,
SUM (IF(SC.type_conn = 'POST',N.size_site,0)) as Traffic_OUT
From news N, status_conn SC, users U
where N.id_conn = SC.id_conn
and N.id_user = U.id_user
and U.name_user = 'max'
and N.date_conn = '2015-08-04'
Group by N.site_name
Order by Traffic_IN
otherwise
select ...
...
Order by 3
You may very well have a parenthesis problem at the end of your query. Try
[...] ORDER BY SUM (IF((SC.type_conn = 'GET') && (SC.type_conn = 'CONNECT')),N.size_site,0)

How to form complex mysql query that has left outer join, aggregate data with group by using SQLAlchemy?

How to write the following query using SQLAlchemy?
SELECT i.itemid, sum(i.quantitysold) total_quantity_sold, max(t.createdAt) last_sale_time
FROM ItemList i LEFT OUTER JOIN ItemTransactions t ON i.itemid = t.itemid
WHERE i.active = 'y'
GROUP BY i.itemid
ORDER BY total_quantity_sold asc;
This is what I ended up writing:
from sqlalchemy.sql import func as sa_func
query = ItemList.query.with_entities(ItemList.itemid)
query = query.outerjoin(ItemTransactions, ItemTransactions.itemid == ItemList.itemid)
query = query.add_columns(sa_func.sum(ItemList.quantitySold).label('total_quantity_sold'))
query = query.add_columns(sa_func.max(ItemTransactions.createdAt).label('last_sale_time'))
query = query.filter(ItemList.active == "y")
query = query.group_by(ItemList.itemid)
query = query.order_by(sa_func.sum(ItemList.quantitySold).asc())
if limit is not None and limit is not 0:
query = query.limit(limit)
if offset is not None:
query = query.offset(offset)
# Execute the query
sales = query.all()
from sqlalchemy.sql import func
query = ItemList.query.with_entities(ItemList.itemid)
query = query.outerjoin(ItemTransactions, ItemTransactions.itemid == ItemList.itemid)
query = query.add_columns(func.sum(ItemList.quantitySold).label('total_quantity_sold'))
query = query.add_columns(func.max(ItemTransactions.createdAt).label('last_sale_time'))
query = query.filter(ItemList.active == "y")
query = query.group_by(ItemList.itemid)
query = query.order_by(func.sum(ItemList.quantitySold).asc())

linq lambda composite key where and group by

what's the linq lambda expression for the following mysql query
Select Count(*), Users.BusinessName From Offers
inner join Users on Users.UserId = Offers.UserId
inner join RoleUsers on RoleUsers.User_UserId = Users.UserId
inner join Roles on Roles.RoleId = RoleUsers.Role_RoleId
where Roles.RoleName = 'Seller'
group by Users.BusinessName
Counts the Number of Offers and Groups it by the User's Name ( where the User is a seller).
public static List<CountsByUser> NoOffersByUserType()
{
List<Offer> offers;
using (MainDb ctx = new MainDb())
{
var role = ctx.Roles.FirstOrDefault(r => r.RoleName == "Seller");
List<User> users = role.Users.ToList();
offers= ctx.OfertaPret.Any(u => u.User == users).ToList();
//here is the problem u.User ==users
}
List<CountsByUser> requests = offers.GroupBy(o => o.User.BusinessName)
.Select(nl => new CountsByUser
{
name = nl.Key,
number = nl.Count()
})
.ToList();
return requests;
}
offers= ctx.OfertaPret.Include(u=>u.User)
.Where(u => u.User.Roles.Any(r => r.RoleName == "Seller")).ToList();

how i write this sql query to linq query

i just want to use LinqToSql classes query. here i just want to convert this sql query to appropriate linq query.
this is my sql query:
SELECT j.[JobID], p.[PreparedEmailID],
p.[Name] AS 'PreparedEmailName',
j.[CreatedOn], j.[CompletedOn],
j.[SubscriberCount], j.[EmailsSent],
(SELECT TOP 1 [Message] FROM
[LoggedMessages] WHERE [JobID] =
j.[JobID] ORDER BY [LoggedMessageID] DESC)
AS 'LoggedMessage' FROM [Jobs] AS j
INNER JOIN [PreparedEmails] AS p
ON p.[PreparedEmailID] =
j.[PreparedEmailID]
and my generated linq query is like:
var query = from j in db.Jobs
join p in db.PreparedEmails on j.PreparedEmailID equals p.PreparedEmailID
join l in db.LoggedMessages on j.JobID equals l.JobID into ej
from l in ej.DefaultIfEmpty() orderby l.LoggedMessageID descending
orderby l.LoggedMessageID descending
orderby j.CreatedOn descending
select new
{
JobID = j.JobID,
PreparedEmailID = p.PreparedEmailID,
PreparedEmailName = p.Name,
CreatedOn = j.CreatedOn,
CompletedOn = j.CompletedOn,
SubscriberCount = j.SubscriberCount,
EmailsSent = j.EmailsSent,
LoggedMsg = l.Message
};
I prepared some linQ query for you (but i didn't test it in VS because i have no access to it now, so please be careful because it can contain some errors):
var list = from Jobs
join PreparedEmails on Jobs.PreparedEmailID == PreparedEmails.PreparedEmailID
join LoggedMessages on LoggedMessages.JobID == Jobs.JobID
select
{
JobID = Jobs.JobID,
PreparedEmailID = PreparedEmails.PreparedEmailID,
PreparedEmailName = PreparedEmails.Name,
CreatedOn= Jobs.CreatedOn,
CompletedOn = Jobs.CompletedOn,
SubscriberCount = Jobs.SubscriberCount,
EmailsSent = Jobs.EmailsSent,
LoggedMessage = LoggedMessages.Message
} orderby descending LoggedMessages.LoggedMessageID;
It should help a little bit ...
this is solution:
var query = from j in db.Jobs
join p in db.PreparedEmails on j.PreparedEmailID equals p.PreparedEmailID
orderby j.CreatedOn descending
select new
{
JobID = j.JobID,
PreparedEmailID = p.PreparedEmailID,
PreparedEmailName = p.Name,
CreatedOn = j.CreatedOn,
CompletedOn = j.CompletedOn,
SubscriberCount = j.SubscriberCount,
EmailsSent = j.EmailsSent,
LoggedMsg = (from l in db.LoggedMessages
where j.JobID == l.JobID
orderby l.LoggedMessageID descending
select l.Message).FirstOrDefault()
};