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()
};
Related
iam trying to convert following ORACLE query into Aurora DB MYSQL query.
Changed few oracle functions to mysql functions.
SELECT MIN(TP.TP_ID) TP_ID,
TC_GRP.TC_GRP_NB TC_GRP_NB,
MIN(TC.TC_ID) TC_ID,
MIN(TC.FAC_ID) FAC_ID,
LISTAGG(TC_GST.TXN_IDVL_PTY_ID, ',') WITHIN GROUP (ORDER BY TC_GST.TXN_IDVL_PTY_ID) AS TXN_IDVL_PTY_ID
FROM RES_MGMT.TP
INNER JOIN RES_MGMT.TPS
ON TPS.TP_ID = TP.TP_ID
INNER JOIN RES_MGMT.TC_GRP
ON TC_GRP.TPS_ID = TPS.TPS_ID
INNER JOIN RES_MGMT.TC
ON (TC.TC_GRP_NB = TC_GRP.TC_GRP_NB AND
TC.TC_TYP_NM = 'AccommodationComponent' AND
TC.TRVL_STS_NM = 'Booked' AND TC.UPGRD_TC_ID IS NULL)
INNER JOIN RES_MGMT.TC_GST
ON TC_GST.TC_ID = TC.TC_ID
WHERE TC_GRP.ADV_INTERNT_CHKIN_IN = 'Y'
AND TPS.SRC_ACCT_CTR_ID = 2
AND TC.FAC_ID in (80010383)
AND TRUNC(TC.TC_STRT_DTS) = TO_DATE('20210930', 'yyyyMMdd')
AND EXISTS (SELECT *
FROM RES_MGMT.TC TC1
WHERE TC1.TC_GRP_NB = TC.TC_GRP_NB
AND TC1.TC_TYP_NM = 'AdmissionComponent'
AND TC1.TRVL_STS_NM = 'Booked')
GROUP BY TC_GRP.TC_GRP_NB;
MySQLQuery has modified as follows:
SELECT MIN(TP.TP_ID) TP_ID,
TC_GRP.TC_GRP_NB TC_GRP_NB,
MIN(TC.TC_ID) TC_ID,
MIN(TC.FAC_ID) FAC_ID,
LISTAGG(TC_GST.TXN_IDVL_PTY_ID, ',') WITHIN GROUP (ORDER BY TC_GST.TXN_IDVL_PTY_ID) AS TXN_IDVL_PTY_ID
FROM RES_MGMT.TP
INNER JOIN RES_MGMT.TPS
ON TPS.TP_ID = TP.TP_ID
INNER JOIN RES_MGMT.TC_GRP
ON TC_GRP.TPS_ID = TPS.TPS_ID
INNER JOIN RES_MGMT.TC
ON (TC.TC_GRP_NB = TC_GRP.TC_GRP_NB AND
TC.TC_TYP_NM = 'AccommodationComponent' AND
TC.TRVL_STS_NM = 'Booked' AND TC.UPGRD_TC_ID IS NULL)
INNER JOIN RES_MGMT.TC_GST
ON TC_GST.TC_ID = TC.TC_ID
WHERE TC_GRP.ADV_INTERNT_CHKIN_IN = 'Y'
AND TPS.SRC_ACCT_CTR_ID = 2
AND TC.FAC_ID in (80010385)
AND DATE(TC.TC_STRT_DTS) = STR_TO_DATE('20210930', '%Y-%m-%d')
AND EXISTS (SELECT *
FROM RES_MGMT.TC TC1
WHERE TC1.TC_GRP_NB = TC.TC_GRP_NB
AND TC1.TC_TYP_NM = 'AdmissionComponent'
AND TC1.TRVL_STS_NM = 'Booked')
GROUP BY TC_GRP.TC_GRP_NB;
Iam getting mysql syntax error near WITHIN GROUP.
Kindly suggest what need to be changed.
I am writing a MySQL query with left join it giving me result in 28 seconds when I remove and condition with left join then it working in one second can any one tell me what is the issue in my query and how it will be modified?
select *
FROM regist_queue rq
left join appoint ap
on rq.token_number = ap.daily_ticket_no
and rq.LocationId = 15800
and ap.LocationId = 15800
and date(rq.QueueDate) = CURRENT_DATE()
and date(ap.dAppDate) = date(now())
left join patient pr
on ap.iPatID = pr.IPatID
left join gender ge
on pr.vGender = ge.iGenderID
where ifnull(ap.isDel,0) = 0
and ifnull(ap.is_referred,0) != 1
and (ap.LocationId = 15800 or rq.LocationId = 15800 )
order by rq.token_number asc;
I also applied indexes on all searched parameters and where joins are applied.
Explain plan of query.
MySQL Query Plan:
Your purpose is not pretty clear to me. For an example in the join and rq.LocationId = 15800
and ap.LocationId = 15800
and in the where clause and (ap.LocationId = 15800 or rq.LocationId = 15800 )
what my suggestion is to have something like this.
in the left join rq.LocationId = ap.LocationId
and in the where clause ap.LocationId = 15800
it is hard to evaluate the performance without having the real data.
Use SQL with (nolock) in sql query
like :
select *
FROM regist_queue rq with (nolock)
left join appoint ap with (nolock)
on rq.token_number = ap.daily_ticket_no
and rq.LocationId = 15800
and ap.LocationId = 15800
and date(rq.QueueDate) = CURRENT_DATE()
and date(ap.dAppDate) = date(now())
left join patient pr with (nolock)
on ap.iPatID = pr.IPatID
left join gender ge with (nolock)
on pr.vGender = ge.iGenderID
where ifnull(ap.isDel,0) = 0
and ifnull(ap.is_referred,0) != 1
and (ap.LocationId = 15800 or rq.LocationId = 15800 )
order by rq.token_number asc;
it seems there is Cartesian join....
base on the three predicate starts with on .........,
i think the sql statement does not based on your real purpose...
I have a query that I want to show results differently depending on a specific field. For example, I am using
$result = $wpdb->get_results( "SELECT `b`.`company` AS `company`,`bp`.`material` AS `material`,
if(((`bp`.`cost` * 1.2) < `ls`.`maximumbid`),(ROUND(`bp`.`cost` * 1.2,2)),ROUND(`bp`.`cost`,2)) AS `newcost`
from (((`windows_brands_products` `bp` left join `windows_brands` `b` on((`bp`.`brand_id` = `b`.`id`)))
join `Windows_last_submissions` `ls`) join `windows_materials` `wm`)
where ((`bp`.`width` = round(`ls`.`width`,0))
and (`bp`.`height` = round(`ls`.`height`,0))
and (`bp`.`material` = `wm`.`name`)
and (`bp`.`type` = `ls`.`type`)
and if((`ls`.`minimumbid` <> '0.00'),(`bp`.`cost` between `ls`.`minimumbid` and `ls`.`maximumbid`),(`bp`.`cost` <= `ls`.`maximumbid`)))
ORDER BY b.company ASC");
The results I want are if the row ls.type = 'Fixed/Picture', I want bp.width = round(ls.width,-1) and still as I have it for any other ls.type
I should be getting correct results from:
select `b`.`company` AS `company`,`bp`.`material` AS `material`,if(((`bp`.`cost` * 1.2) < `ls`.`maximumbid`),round((`bp`.`cost` * 1.2),2),round(`bp`.`cost`,2)) AS `newcost` from (((`windows_brands_products` `bp` left join `windows_brands` `b` on((`bp`.`brand_id` = `b`.`id`))) join `Windows_last_submissions` `ls`) join `windows_materials` `wm`)
where if((`ls`.`type` = 'Fixed/Picture'),(`bp`.`width` = round(`ls`.`width`,-2),(`bp`.`width` = round(`ls`.`width`,0)) and (`bp`.`height` = round(`ls`.`height`,0)) and (`bp`.`material` = `wm`.`name`) and (`bp`.`type` = `ls`.`type`) and if((`ls`.`minimumbid` <> '0.00'),(`bp`.`cost` between `ls`.`minimumbid` and `ls`.`maximumbid`),(`bp`.`cost` <= `ls`.`maximumbid`))) order by `b`.`company`
but it keeps giving me syntax errors as I try to correct the query which I'm not succeeding.
The point is retrieve a broader range of results if the type is 'Fixed/Picture'
Thank you,
Casey
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())
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