how to pass select subquery in where clause using laravel - laravel

This is my SQl query
select sum(stock.total_in_stock) as total_in_stock
,stock.name
,stock.inventory_id
from (
select i.store_id
,i.model_id
,i. total_in_stock
,i.id as inventory_id
, m.*
from `inventory` as `i`
left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id`
left join `model` as `m` on `m`.`id` = `ms`.`model_id`
where `i`.`model_id` = m.id
and `m`.`status` = 1
and `ms`.`status` = 1
and `i`.`created_at` = (
select si.created_at
from inventory AS si
where si.model_id = i.model_id
and si.store_id = i.store_id
and si.status=1
order by si.created_at desc limit 1
)
) as stock
group by stock.model_id
In laravel, it is written as this:
$results1 = DB::table('inventory as i')
->select(DB::raw( 'sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* '))
->leftJoin('model_store as ms','ms.store_id','=','i.store_id')
->leftJoin('model as m','m.id','=','ms.model_id')
->where('i.model_id','=', 'm.id')
->where('m.status','=', '1')
->where('ms.status','=', '1')
->where("i.created_at","=",function($query) {
$query->select(DB::raw("si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1)) as stock GROUP BY stock.model_id"));
});
It gives me the following error:-
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: select sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* from `inventory` as `i` left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id` left join `model` as `m` on `m`.`id` = `ms`.`model_id` where `i`.`model_id` = m.id and `m`.`status` = 1 and `ms`.`status` = 1 and `i`.`created_at` = (select si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1 )) as stock GROUP BY stock.model_id))
It takes 2 closing brackets at the end and gives the above error. Please help me writing the above SQL query in laravel.

Answering your question that's in the tile: the subquery where needs fix:
->where("i.created_at", function($query) {
$query->from('inventory as si')
->selectRaw('max(si.created_at)')
->whereRaw('si.model_id = i.model_id AND ...');
});
However, in order to create a subquery in the from clause, you need to pass raw query, so your whole code requires a bit of toSql() and setBindings(...), which is cumbersome.
So to get the answer to your problem, better describe the problem itself instead.

Related

JPQL query with having oracle db

I am using jpql jpa eclipselink Following query wont work :
SELECT c FROM TableA c WHERE c.forumId = :forumId AND c.isDefault = true HAVING MAX (c.validFrom)
The error im getting "The expression is not a valid conditional expression"
The HAVING clause only works with a GROUP BY expression.
The HAVING clause allows for the results of a GROUP BY to be filtered.
Your question is:
i want o get max validFrom how can i make expression ot of this
But you can make a query without GROUP BY and HAVING to do what you want:
select c from TableA c WHERE c.validFrom = (
SELECT MAX(c2.validFrom)
FROM TableA c2
WHERE c2.Id = c.Id AND c.forumId = :forumId AND c.isDefault = true
)
If you would like to use GROUP BY and HAVING, you can do:
SELECT c FROM TableA c WHERE c.validFROM = (
SELECT MAX(validFROM)
FROM TableA
WHERE forumId = :forumId AND isDefault = true
GROUP BY validFROM
HAVING validFROM=c.validFROM
)

How to update and set values based on multiple joins in select statment?

I want to update a column prtnum and revlvl in table invdtl based on value from select statment, here is the code
update invdtl set invdtl.prtnum = usr_prtmst_xref.prtnum,invdtl.revlvl =
usr_prtmst_xref.colnam ([select
invdtl.prtnum,usr_prtmst_xref.prtnum AS
crossref,invdtl.revlvl,aremst.arecod,aremst.fwiflg from invdtl
join usr_prtmst_xref
on usr_prtmst_xref.prtnum = usr_prtmst_xref.prtnum
join invsub
join invlod
join locmst
join aremst
on aremst.arecod = locmst.arecod
and aremst.wh_id = locmst.wh_id
on locmst.stoloc = invlod.stoloc
and locmst.wh_id = invlod.wh_id
on invlod.lodnum = invsub.lodnum
on invsub.subnum = invdtl.subnum where aremst.arecod = 'EXPR' or
aremst.fwiflg = '1' and rownum <2])
I want to copy two values prtnum and revlvl that are returned by select statement but there is some syntax issue.
There are a bunch of errors here:
The syntax for a multi-column update is basically
update blah
set ( col1, col2 ) = ( select x, y
from
...
)
The syntax for multiple joins is basically
from table1 t1
join table2 t2
on t1.col = t2.col
join table3 t2 on
t2.col = ...
Get ride of "[" and "]"
The predicate rownum<2 is probably to get around the message you received, something like "single row sub-query returns more than 1
row" Which this predicate "fixes" that problem, you are just getting
the first random row; probably not what you want. You probably need to
correlate the sub-query with the update
I would fix these basic syntax errors and try again.

ORA-01427: Subquery returns more than one row

When I execute the query below, I get the message like this: "ORA-01427: Sub-query returns more than one row"
Define REN_RunDate = '20160219'
Define MOP_ADJ_RunDate = '20160219'
Define RID_RunDate = '20160219'
Define Mbr_Err_RunDate = '20160219'
Define Clm_Err_RunDate = '20160219'
Define EECD_RunDate = '20160219'
select t6.Member_ID, (Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err,
NVL(Claim_Sent_Amt,0) Sent_Claims, Rejected_Claims,Orphan_Claim_Amt,Claims_Accepted, MOP_Adj_Sent Sent_MOP_Adj,Net_Sent,
(Case
When Net_Sent < 45000 then 0
When Net_Sent > 25000 then 20500
Else
Net_Sent - 45000
End
)Net_Sent_RI,
' ' Spacer,
Total_Paid_Claims CMS_Paid_Claims, MOP_Adjustment CM_MOP_Adj, MOP_Adjusted_Paid_claims CM_Net_Claims, Estimated_RI_Payment CM_RI_Payment
from
(
select NVL(t3.Member_ID,t5.Member_ID)Member_ID, t3.Claim_Sent_Amt, NVL(t4.Reject_Claims_Amt,0) Rejected_Claims, NVL( t8.Orphan_Amt,0) Orphan_Claim_Amt,
(t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0) - NVL(t8.Orphan_Amt,0)) Claims_Accepted,
NVL(t2.MOP_Adj_Amt,0) MOP_Adj_Sent ,
( (t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0)) - NVL(t2.MOP_Adj_Amt,0) - NVL(t8.Orphan_Amt,0) ) Net_Sent,
t5.Member_ID CMS_Mbr_ID,t5.Total_Paid_Claims,t5.MOP_Adjustment, t5.MOP_Adjusted_Paid_Claims, t5.Estimated_RI_Payment
From
(
Select t1.Member_ID, Sum( t1.Paid_Amount) Claim_Sent_Amt
From RENS t1
where t1.rundate = &REN_RunDate
group by t1.Member_ID
) t3
Left Join MOP_ADJ t2
on (t3.Member_ID = t2.Member_ID and t2.rundate = &MOP_ADJ_RunDate)
Left Join
(select Member_ID, sum(Claim_Total_Paid_Amount) Reject_Claims_Amt from CLAIM_ERR
where Rundate = &Claim_Err_RunDate
and Claim_Total_Paid_Amount != 0
Group by member_ID
)t4
on (t4.Member_ID = t3.Member_ID )
Full Outer Join
(
select distinct Member_ID,Total_Paid_Claims,MOP_Adjustment,MOP_Adjusted_Paid_Claims, Estimated_RI_Payment
from RID
where Rundate = &RID_RunDate
and Estimated_RI_Payment != 0
)t5
On(t5.Member_ID = t3.Member_ID)
Left Outer Join
(
select Member_ID, Sum(Claim_Paid_Amount) Orphan_Amt
From EECD
where RunDate = &EECD_RunDate
group by Member_ID
)t8
On(t8.Member_ID = t3.Member_ID)
)t6
order by Member_ID
You have this expression among the select columns (at the top of your code):
(Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID
and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err
If you want to select the literal 'Y', then just select 'Y' as Mbr_Err. If you want to select either 'Y' or null, depending on whether the the subquery returns exactly one row or zero rows, then write it that way.
I suspect this subquery (or perhaps another one in your code, used in a similar way) returns more than one row - in which case you will get exactly the error you got.

laravel query builder from normal query

DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
b.transaction_code,b.amount from bill_det a left join
(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no ) b
on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));
this is normal query.change into laravel query?.
i tried.
$bill=DB::table('bill_det')->leftJoin('payment_transactions', 'bill_det.bill_no', '=', 'payment_transactions.bill_no')
->select('bill_det.bill_no','bill_det.account_id','bill_det.bill_date','bill_det.amount_paid',
'payment_transactions.transaction_code',DB::raw('sum(payment_transactions.amount) as amount'))
->where('payment_transactions.status','=','success')
->where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))
->groupBy('bill_det.bill_no')
->orderBy('bill_det.bill_no','desc');
i can't compare -> where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))
i used like this ->whereRaw('bill_det.amount_paid != sum(payment_transactions.amount)')
{"error":{"type":"Illuminate\Database\QueryException","message":"SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select count(*) as aggregate from (select '1' as row_count from bill_det left join payment_transactions on bill_det.bill_no = payment_transactions.bill_no where payment_transactions.status = success and bill_det.amount_paid != sum(payment_transactions.amount) group by bill_det.bill_no order by bill_det.bill_no desc) count_row_table)"
DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
b.transaction_code,b.amount from bill_det a left join
(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no ) b
on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));
After converting this to laravel Query::
$query = \Illuminate\Support\Facades\DB::table('bill_det')
->select('a.bill_no', 'a.account_id', 'a.bill_date', 'a.amount_paid', 'b.transaction_code', 'b.amount')
->leftJoin(DB::raw('(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no) b'), function($join) {
$join->on('a.bill_no', '=', 'b.bill_no');
})
->where('a.amount_paid','<>', 'b.amount')
->orderBy('b.bill_no')
->get();
In case you want to know how to use raw expression inside where then use this:
$query->whereRaw(DB::raw('(your expression!!)'));

Hierarchical query when used as sub query gives : ORA-00911: invalid character

I have been trying to execute the following query and its throwing me following error:
ORA-00911: invalid character
select
sum(coalesce(decode(FKTD_DR_CR_TYPE,'1',FKTD_NRS_AMOUNT,0),0)) as DEBIT_AMOUNT,
sum(coalesce(decode(FKTD_DR_CR_TYPE,'0',FKTD_NRS_AMOUNT,0),0)) as CREDIT_AMOUNT
from FMS_KS_TRANS_DTL
inner join FMS_KS_TRANS_MST
ON FMS_KS_TRANS_MST.FKTM_TRANS_MST_ID = FMS_KS_TRANS_DTL.FKTD_TRANS_MST_ID
inner join FMS_FC_VOUCHER_CONFIG
ON FMS_FC_VOUCHER_CONFIG.FFVC_VOUCHER_ID = FMS_KS_TRANS_MST.FKTM_VOUCHER_ID
where FFVC_ACCOUNT_TYPE = 5 and FKTM_FISCAL_YEAR='2066/67'
and FKTD_ACC_ID in
(
select FFAM_ACC_ID from FMS_FC_ACC_MST
where ffam_group_flag = 2 and FFAM_FISCAL_YEAR='2066/67'
start with ffam_acc_id in
(
select distinct FKP_CASH_ACC_ID from FMS_KS_PARAMETER
where FKP_FISCAL_YEAR='2066/67'
)
connect by ffam_group_flag = 2
and prior ffam_acc_id = ffam_upper_acc_id;
/*
This sub query executes fine if executed separately
and this whole query block executes fine if
this hierarchical query is not used.
*/
)
A semicolon before commented query?
A subquery should not end with a ;
select
sum(coalesce(decode(FKTD_DR_CR_TYPE,'1',FKTD_NRS_AMOUNT,0),0)) as DEBIT_AMOUNT,
sum(coalesce(decode(FKTD_DR_CR_TYPE,'0',FKTD_NRS_AMOUNT,0),0)) as CREDIT_AMOUNT
from FMS_KS_TRANS_DTL
inner join FMS_KS_TRANS_MST
ON FMS_KS_TRANS_MST.FKTM_TRANS_MST_ID = FMS_KS_TRANS_DTL.FKTD_TRANS_MST_ID
inner join FMS_FC_VOUCHER_CONFIG
ON FMS_FC_VOUCHER_CONFIG.FFVC_VOUCHER_ID = FMS_KS_TRANS_MST.FKTM_VOUCHER_ID
where FFVC_ACCOUNT_TYPE = 5 and FKTM_FISCAL_YEAR='2066/67'
and FKTD_ACC_ID in
(
select FFAM_ACC_ID from FMS_FC_ACC_MST
where ffam_group_flag = 2 and FFAM_FISCAL_YEAR='2066/67'
start with ffam_acc_id in
(
select distinct FKP_CASH_ACC_ID from FMS_KS_PARAMETER
where FKP_FISCAL_YEAR='2066/67'
)
connect by ffam_group_flag = 2
and prior ffam_acc_id = ffam_upper_acc_id
);
should work I guess (semicolon moved), unless there is something else which is wrong :-)

Resources