Sum in laravel db query - laravel

I need to get the Sum of ProductQTY groupBy ProductID while using join, I always get an error when using db::raw, attached here is my code
$pick_list_items = DB::table('pick_list_detail')
->where('pick_list_detail.pick_list_id',$id)
->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
->select(['pick_list_detail.sale_invoice_id', 'sale_invoice_detail.product_id', 'sale_invoice_detail.product_qty', 'sale_invoice_detail.uom', 'sale_invoice_detail.uom_factor'])
->sum('sale_invoice_detail.product_qty')
->groupBy('sale_invoice_detail.product_id')
->get();
I'm using laravel 5.4
Here is the error
(2/2) QueryException
SQLSTATE[42000]: Syntax error or access violation: 1055 'fdis.pick_list_detail.sale_invoice_id' isn't in GROUP BY (SQL: select
pick_list_detail.sale_invoice_id,
sale_invoice_detail.product_id,
sale_invoice_detail.product_qty, sale_invoice_detail.uom,
sale_invoice_detail.uom_factor from pick_list_detail inner join
sale_invoices on pick_list_detail.sale_invoice_id =
sale_invoices.id inner join sale_invoice_detail on
sale_invoice_detail.sale_invoice_id =
pick_list_detail.sale_invoice_id where
pick_list_detail.pick_list_id = 1 group by
sale_invoice_detail.product_id)

$sale_invoices = DB::table('pick_list_detail')
->select(DB::raw('sum(sale_invoice_detail.product_qty) as si_count, pick_list_detail.pick_list_id , sale_invoice_detail.product_id , sale_invoice_detail.uom, sale_invoice_detail.uom_factor '))
->where('pick_list_detail.pick_list_id',$id)
->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
->groupBy('pick_list_detail.pick_list_id')
->groupBy('sale_invoice_detail.product_id')
->groupBy('sale_invoice_detail.uom')
->groupBy('sale_invoice_detail.uom_factor')
->get();
Raw Query is my solution.

Related

How to write raw query in Laravel?

There is a query:
SELECT ST_DistanceSpheroid(geometry(location), ST_GeomFromText('POINT(37.854289 55.685333)'), 'SPHEROID["WGS 84",6378137,298.257223563]')
FROM users
How to pass parameter 37.854289 55.685333?
Also I tried this:
$point = "37.854289 55.685333";
return DB::table('users')
->select(DB::raw('ST_DistanceSpheroid(geometry(location), ST_GeomFromText(\'POINT(?)\'), \'SPHEROID["WGS 84",6378137,298.257223563]\''), [$point])
->get();
I got this error:
"message": "stripos(): Argument #1 ($haystack) must be of type string, array given",
My attempt bases accepted question:
$lon = 37.857397;
$lat = 55.685333;
return DB::table('users')
->selectRaw(
"(ST_DistanceSpheroid(
geometry(location),
ST_GeomFromText('POINT(? ?)'),
'SPHEROID[?, ?, ?]'
)) as distance",
[$lon, $lat, 'WGS 84', 6378137, 298.257223563]
)->leftJoin('doctors', 'doctors.user_id', 'users.id')->orderBy('distance', 'ASC')->get();
I have got an error:
{
"message": "PDO: SQLSTATE[XX000]: Internal error: 7 ОШИБКА: SPHEROID parser - couldnt parse the spheroid\nLINE 4: 'SPHEROID[?, ?, ?]'\n ^ (SQL: select (ST_DistanceSpheroid(\n geometry(location),\n ST_GeomFromText('POINT(37.857397 55.685333)'),\n 'SPHEROID[WGS 84, 6378137, 298.257223563]'\n )) as distance from \"users\" left join \"doctors\" on \"doctors\".\"user_id\" = \"users\".\"id\" order by \"distance\" asc)"
}
The row query that works:
SELECT doctors.user_id, (ST_DistanceSpheroid(geometry(location), ST_GeomFromText('POINT(37.857397 55.690576)'), 'SPHEROID["WGS 84",6378137,298.257223563]')
) as distance FROM users INNER JOIN doctors ON doctors.user_id = users.id ORDER BY distance ASC
You almost got it. The [$point] parameter should be the second parameter of DB::raw($query, $bindings) but you added it as a second parameter to select().
// What you have
->select(DB::raw(...), [$point])
// correct syntax
->select(DB::raw(..., [$point]))
If you've got nothing else to put in your select clause, might as well use selectRaw(). It's the same as select(DB::raw()).
DB::table('users')
->selectRaw('ST_DistanceSpheroid(geometry(location), ST_GeomFromText(\'POINT(?)\'), \'SPHEROID["WGS 84",6378137,298.257223563]\')', [$point])
Personally, I'd write the query like this:
$query = DB::table('users')
->selectRaw(
"ST_DistanceSpheroid(
geometry(location),
ST_GeomFromText('POINT(? ?)'),
'SPHEROID[?, ?, ?]'
)",
[37.854289, 55.685333, 'WGS 84', 6378137, 298.257223563]
)
->get();

How to combined duplicate row to one row in laravel 5.7 controller

I want to combined the duplicate row to one row and show the result in front end but i face some error please any one help .
time_session | day
------------ ----
1 saturday
2 friday
2 friday
3 wednessday
this is my controller code:
public function classSchedule()
{
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*')
->groupBy('applications.time_session')
->get();
return view('backEnd.classes.manageClass1',['duplicates'=>$duplicates]);}
this is my front end code:
<td> {{$duplicate->time_session }} </td>
time_session | day taking day
------------ ---- ----------
1 saturday 1
2 friday 2
3 wednessday 1
SQLSTATE[42000]: Syntax error or access violation: 1055 'pixelmetro.applications.id' isn't in GROUP BY (SQL: select `applications`.*, `batches`.* from `applications` inner join `batches` on `applications`.`time_session` = `batches`.`id` group by `applications`.`time_session`)
Actual out put :
https://www.facebook.com/photo.php?fbid=2317443465016247&set=pcb.442972496253366&type=3&theater&ifg=1
This 1055 error is a MySQL issue that can be resolved changing Laravel config. Go to config/database.php file and change mysql property strict from true to false. 'strict' => false,
If you don't want to change it, then you can add a new property modes
'modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
And yeah don't forget to run the command php artisan config:cache after making changes.
To get desired result you need to use count.
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*', DB::raw('COUNT(applications.time_session) as counter')
->groupBy('applications.time_session')
->get();
In blade:
#foreach($duplicates as $duplicate)
<td>$duplicate->counter</td>
#endforeach
i think you have some miss conception on group by.if you group by with a certain column then you have to get others column with aggregate function.
in your case you made group by with (time_session) and you try to get all from the table that's why you got the error.
solution: you can make group by with both (time_session and day) then your problem will be solve.
sample code:
public function classSchedule()
{
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*')
->groupBy('applications.time_session')
->groupBy('applications.day')
->get();
return view('backEnd.classes.manageClass1',['duplicates'=>$duplicates]);}

Eloquent: Complex Script

Good day!
can be possible to change this script to Eloquent Laravel
SELECT concat(firstname, " ",lastname) as fullname,q_title,answer FROM `user_pivot_survey_answer` as upsa
LEFT JOIN (SELECT id,q_title FROM survey_question) sq ON upsa.qid = sq.id
LEFT JOIN (SELECT id,firstname,lastname FROM user_survey_answer) usa ON upsa.sid = usa.id
I translate it already to Eloquent, however, I don't know if is working
$testquery = DB::table('user_pivot_survey_answer')
->leftJoin(DB::select('SELECT id,q_title FROM survey_question'),function($join)) {
$join->on('user_pivot_survey_answer.id', '=', 'survey_question.id');
})
->leftJoin(DB::select('SELECT id,firstname,lastname FROM user_survey_answer'),function($join){
$join->on('user_pivot_survey_answer.id', '=', 'user_survey_answer.id');
});
Thanks
Use this:
$testquery = DB::table('user_pivot_survey_answer as upsa')
->select(DB::raw('concat(firstname, " ", lastname) as fullname'), 'q_title', 'answer')
->leftJoin(DB::raw('(SELECT id,q_title FROM survey_question) sq'), 'upsa.qid', 'sq.id')
->leftJoin(DB::raw('(SELECT id,firstname,lastname FROM user_survey_answer) usa'), 'upsa.sid', 'usa.id');

column ambiguously defined even though all the selected columns are prefixed, while creating view

CREATE OR REPLACE VIEW V_DU_NBO_CAMPAIGN
AS
SELECT PMM_UPSELL_CAMPAIGN.STATUS, PMM_UPSELL_CAMPAIGN.TEST_EPOCH, DU_NBO_CAMPAIGN.*, OFFER_MSG_OFFERMESSAGE.TEXT AS OFFER_MSG_OFFERMESSAGE, NULL AS AWARD_MSG, REMINDER_MSG_REMINDERMESSAGE.TEXT AS REMINDER_MSG_REMINDERMESSAGE, PMM_PROGRAM.BASE_TIMEZONE, PMM_UPSELL_CAMPAIGN.CAMPAIGN_TEMPLATE, PMM_UPSELL_CAMPAIGN.TASKS_SUBMITTED, PMM_UPSELL_CAMPAIGN.TASKS_EVALUATED, PMM_UPSELL_CAMPAIGN.TASKS_COMPLETED, PMM_UPSELL_CAMPAIGN.EMITS, PMM_UPSELL_CAMPAIGN.LAST_EVALUATION, PMM_UPSELL_CAMPAIGN.LAST_PREEVALUATION, PMM_UPSELL_CAMPAIGN.TARGET_LIST_JOB_STATUS, PMM_UPSELL_CAMPAIGN.TARGET_LIST_TYPE, PMM_UPSELL_CAMPAIGN.TARGET_LIST_ID, PMM_UPSELL_CAMPAIGN.PENDING_TIME, PMM_UPSELL_CAMPAIGN.STARTING_TIME, PMM_UPSELL_CAMPAIGN.OFFERING_TIME, PMM_UPSELL_CAMPAIGN.OPEN_TIME, PMM_UPSELL_CAMPAIGN.SUSPENDED_TIME, PMM_UPSELL_CAMPAIGN.COMPLETE_TIME, PMM_UPSELL_CAMPAIGN.FAILED_TIME, PMM_UPSELL_CAMPAIGN.KILLED_TIME, PMM_UPSELL_CAMPAIGN.LAST_UPDATE_TIME
FROM
DU_NBO_CAMPAIGN
LEFT JOIN
PMM_UPSELL_CAMPAIGN
ON PMM_UPSELL_CAMPAIGN.CAMPAIGNID = DU_NBO_CAMPAIGN.CAMPAIGNID
LEFT JOIN
PMM_PROGRAM
ON PMM_PROGRAM.PROGRAM_ID = DU_NBO_CAMPAIGN.PROGRAM_ID
LEFT JOIN
DU_NBO_CAMPAIGN_MSG OFFER_MSG_OFFERMESSAGE
ON DU_NBO_CAMPAIGN.PROGRAM_ID = OFFER_MSG_OFFERMESSAGE.PROGRAM_ID
AND DU_NBO_CAMPAIGN.CAMPAIGNID = OFFER_MSG_OFFERMESSAGE.CAMPAIGNID
AND PMM_PROGRAM.DEFAULT_LANGUAGE = OFFER_MSG_OFFERMESSAGE."LANGUAGE"
AND OFFER_MSG_OFFERMESSAGE.MESSAGEID = 'NBO_SMS_OFFER'
LEFT JOIN
DU_NBO_CAMPAIGN_MSG OFFER_MSG_OFFERMESSAGE
ON DU_NBO_CAMPAIGN.PROGRAM_ID = OFFER_MSG_OFFERMESSAGE.PROGRAM_ID
AND DU_NBO_CAMPAIGN.CAMPAIGNID = OFFER_MSG_OFFERMESSAGE.CAMPAIGNID
AND PMM_PROGRAM.DEFAULT_LANGUAGE = OFFER_MSG_OFFERMESSAGE."LANGUAGE"
AND OFFER_MSG_OFFERMESSAGE.MESSAGEID = 'NBO_SMS_AWARD'
LEFT JOIN
DU_NBO_CAMPAIGN_MSG REMINDER_MSG_REMINDERMESSAGE
ON DU_NBO_CAMPAIGN.PROGRAM_ID = REMINDER_MSG_REMINDERMESSAGE.PROGRAM_ID
AND DU_NBO_CAMPAIGN.CAMPAIGNID = REMINDER_MSG_REMINDERMESSAGE.CAMPAIGNID
AND PMM_PROGRAM.DEFAULT_LANGUAGE = REMINDER_MSG_REMINDERMESSAGE."LANGUAGE"
AND REMINDER_MSG_REMINDERMESSAGE.MESSAGEID = 'NBO_SMS_REMINDER'
ORDER BY DU_NBO_CAMPAIGN.SCHEDULED_DAY DESC, DU_NBO_CAMPAIGN.SCHEDULED_HOUR DESC, DU_NBO_CAMPAIGN.NAME ASC;
I get this error when running above in Sql Developer:-
Error at Command Line:1 Column:0
Error report:
SQL Error: ORA-00918: column ambiguously defined
00918. 00000 - "column ambiguously defined"

Hive returns a non specific error : FAILED: SemanticException java.lang.reflect.UndeclaredThrowableException

I have the following query in HIVE, but it doesn't work
SELECT
newcust.dt , aspen.Probe , newcust.direction , aspen.VLan , sum(newcust.npacket), sum(newcust.nbyte), sum(newcust.nbytetcp), sum(newcust.nbyteudp), sum(newcust.byte_unknown), sum(newcust.pack_unknown), sum(newcust.byte_web), sum(newcust.pack_web), sum(newcust.byte_webapp), sum(newcust.pack_webapp), sum(newcust.byte_residential), sum(newcust.pack_residential), sum(newcust.byte_download), sum(newcust.pack_download), sum(newcust.byte_news), sum(newcust.pack_news), sum(newcust.byte_mail), sum(newcust.pack_mail), sum(newcust.byte_db), sum(newcust.pack_db), sum(newcust.byte_routing), sum(newcust.pack_routing), sum(newcust.byte_encrypted), sum(newcust.pack_encrypted), sum(newcust.byte_office), sum(newcust.pack_office), sum(newcust.byte_vpn), sum(newcust.pack_vpn), sum(newcust.byte_tunneling), sum(newcust.pack_tunneling), sum(newcust.byte_others), sum(newcust.pack_others), sum(newcust.byte_remoteaccess), sum(newcust.pack_remoteaccess), sum(newcust.byte_streaming), sum(newcust.pack_streaming) , sum(newcust.byte_chat), sum(newcust.pack_chat), sum(newcust.byte_voip), sum(newcust.pack_voip), aspen.CustomerName, aspen.General_NetworkPriority, aspen.SLA_CIR, aspen.SLA_EIR
FROM
newcust INNER JOIN aspen ON( aspen.Probe = newcust.numsonde AND aspen.VLan = substring(newcust.name1,1,instr(newcust.name1, '_')-1) )
WHERE
newcust.numsonde = '1'
AND newcust.direction = '0'
AND newcust.dt LIKE '2012-01-20-%%%%'
AND COALESCE(UNIX_TIMESTAMP(aspen.scd_end,'dd-MM-yyyy'),CAST(9999999999 AS BIGINT)) >= UNIX_TIMESTAMP(newcust.dt,'yyyy-MM-dd-HHmm')+cast((newcust.period * 360) as BIGINT)
AND UNIX_TIMESTAMP(aspen.scd_start,'dd-MM-yyyy') < UNIX_TIMESTAMP(newcust.dt,'yyyy-MM-dd-HHmm')+cast((newcust.period * 360) as BIGINT)
GROUP BY newcust.dt, aspen.Probe, newcust.direction, aspen.VLan, aspen.CustomerName, aspen.General_NetworkPriority, aspen.SLA_CIR, aspen.SLA_EIR, from_unixtime(UNIX_TIMESTAMP(newcust.dt,'yyyy-MM-dd-HHmm')+cast((newcust.period * 360) as BIGINT))
Hive returns the following error :
FAILED: SemanticException java.lang.reflect.UndeclaredThrowableException. But there is no other explaination about the root of the problem.
Do you think the query is invalid or is it another "deeper" issue?
Make sure you include all the fields which are there in the select clause are included in group by clause.

Resources