Laravel - how do i get the count data in query? - database

This is the query in mysql
select e_id, h_name,
d_name,drf_name,credit_num,is_required,e_semester,stdate,endate,c_month,num
from(SELECT electcourse.id e_id,
h_id,d_id,ref_id,e_semester,stdate,endate,c_month,count(e_id) as num
FROM electcourse left join period on p_id= period.id left join
hospitalxdepartment on hd_id= hospitalxdepartment.id left join
board on electcourse.id= e_id where st_id= 'admin' group by
e_id) T left join hospital on h_id = hospital.id left join
department on d_id = department.id left join
departmentreference on ref_id = drfid where df_semester=105
This is my query in the laravel, but it got some error message.
public function get_course($st_id,$semester){
$from=DB::table('electcourse')
->selectRaw('electcourse.id as e_id','h_id','d_id','ref_id','e_semester','stdate','endate','c_month','count(e_id) as num',)
->leftjoin('period','p_id','period.id')
->leftjoin('hospitalxdepartment','hd_id','hospitalxdepartment.id')
->leftjoin('board','electcourse.id','e_id')
->where('st_id','=',$st_id)
->where('e_semester','=',$semester)
->groupBy('e_id');
$query=DB::query()
->select('e_id','h_name','d_name','drf_name','credit_num','is_required','e_semester','stdate','endate','c_month')
->fromSub($from, 'T')
->leftjoin('hospital','h_id','hospital.id')
->leftjoin('department','d_id','department.id')
->leftjoin('departmentreference','ref_id','drfid')
->where('df_semester','=',$semester)->orderBy('c_month')->get();
return $query;
}
I make sure it will be work if i didnt use count in the "select" string.
Have anyone know how to fix it with the correct count method?
error message : "Class App\Repositories\BoardRepository does not
exist"
This is mean DB format is wrong.

I find a way to generate a correct query, but it will get error message.
query function
public function get_course($st_id,$semester){
$from=DB::table('electcourse')
->select('electcourse.id as e_id','h_id','d_id','ref_id','e_semester','stdate','endate','c_month',DB::raw('count(e_id) as num'))
->leftjoin('period','p_id','period.id')
->leftjoin('hospitalxdepartment','hd_id','hospitalxdepartment.id')
->leftjoin('board','electcourse.id','e_id')
->where('st_id','=',$st_id)
->where('e_semester','=',$semester)
->groupBy('e_id');
$query=DB::query()
->select('e_id','h_name','d_name','drf_name','credit_num','is_required','e_semester','stdate','endate','c_month')
->fromSub($from, 'T')
->leftjoin('hospital','h_id','hospital.id')
->leftjoin('department','d_id','department.id')
->leftjoin('departmentreference','ref_id','drfid')
->where('df_semester','=',$semester)->orderBy('c_month')->get();
return $query;
}
Error message :
"SQLSTATE[42000]: Syntax error or access violation: 1055
'yangming567.electcourse.id' isn't in GROUP BY (SQL: select e_id,
h_name, d_name, drf_name, credit_num, is_required,
e_semester, stdate, endate, c_month from (select
electcourse.id as e_id, h_id, d_id, ref_id, e_semester,
stdate, endate, c_month, count(e_id) as num from electcourse
left join period on p_id = period.id left join
hospitalxdepartment on hd_id = hospitalxdepartment.id left
join board on electcourse.id = e_id where st_id = admin and
e_semester = 105 group by e_id) as T left join hospital on
h_id = hospital.id left join department on d_id =
department.id left join departmentreference on ref_id =
drfid where df_semester = 105 order by c_month asc)
However, i copy this error message query to Mysql, and it is work!!!!
Have anyone know how to fix my query in laravel?

Related

How can I use outer join with subquery and groupby?

Tool : MySQL Workbench 6.3
Version : MySQL 5.7
SELECT *
FROM cars as a, battery_log as b
WHERE a.user_seq = 226 AND a.seq = b.car_seq
AND b.created = ( SELECT MAX(created) FROM battery_log WHERE car_seq = a.seq )
GROUP BY car_type
ORDER BY a.created DESC;
I want to turn this query into an outer join.
By searching user_seq in the'cars' table
I need to get the latest value of the battery log in the one-to-many relationship of the corresponding car table.
Sometimes the battery log does not have a value that matches car seq, so it is truncated from the joining process of table a and table b. How can I fix this?
SELECT a.*, b.battery
FROM cars as a
LEFT OUTER JOIN battery_log as b ON a.seq = b.car_seq
LEFT OUTER JOIN ( SELECT MAX(created) FROM battery_log WHERE a.seq = b.car_seq) as c
ON b.created = c.MAX(created)
WHERE a.user_seq = 226
GROUP BY car_type
ORDER BY a.created DESC
I tried to fix it this way, but I got the following error:
Error Code: 1054, Unknown column'a.seq' in'where clause'
I solved this problem like this.
SELECT *
FROM cars as a
LEFT OUTER JOIN battery_log as b ON a.seq = b.car_seq
AND b.created = (SELECT MAX(created) FROM battery_log WHERE car_seq = b.car_seq)
WHERE a.user_seq = 226
GROUP BY car_type
ORDER BY a.created DESC;
After LEFT OUTER JOIN ... ON, an additional condition was given with AND, and the query was performed according to the condition.

I get wrong result when calculating weight

I have this query
SELECT ProjInfo.ProjectN AS BS,
ProjShipp.Parts,
SUM(CASE
WHEN DailyPaProd.FK_idNextProcess = 13
AND ProjInfo.FK_Status != 'VENDRE DES MATIERES PREMIERES' THEN ProjShipp.[Weight] * DailyPaProd.[Quantity]
ELSE 0
END) AS [weight fab],
SUM(ProjShipp.[Weight] * ProjShipp.ShippingNavisionQty) AS [weight Shipp]
FROM ProjectShipping ProjShipp
INNER JOIN ProjectInfo ProjInfo ON ProjInfo.id = ProjShipp.IdProject
INNER JOIN DailyPaintProduction DailyPaProd ON DailyPaProd.FK_idPartShip = ProjShipp.id
WHERE ProjInfo.ProjectN = 'BS-00799'
GROUP BY ProjInfo.ProjectN,
ProjShipp.Parts,
ProjShipp.[Weight];
when I run it I get this result
All result are correct except for TA1 on weight Shipp column I'm supposed to get 2352 instead of 11760.Why i am getting this error ,and how to fix it
Thanks in advance.
Update
ProjectShipping table
ProjectInfo table
DailyPaintProduction table
This query worked for me
SELECT ProjInfo.ProjectN AS BS,
ProjShipp.Parts,
(Select SUM(ProjectShipping.[Weight]*DailyPaintProduction.[Quantity])
from DailyPaintProduction
Inner Join ProjectShipping on ProjectShipping.id=DailyPaintProduction.FK_idPartShip
Inner Join ProjectInfo on ProjectInfo.id=ProjectShipping.IdProject
Where DailyPaintProduction.FK_idPartShip=ProjShipp.id and
FK_idNextProcess=13 and
ProjectInfo.FK_Status!='VENDRE DES MATIERES PREMIERES')AS 'weight fab',
SUM(ProjShipp.[Weight]*ShippingNavisionQty)AS 'weight Shipp'
From ProjectShipping ProjShipp
Inner Join ProjectInfo ProjInfo on ProjInfo.id=ProjShipp.IdProject
WHERE ProjInfo.ProjectN = 'BS-00799'
GROUP BY ProjInfo.ProjectN,
ProjShipp.Parts,
ProjShipp.[Weight],
ProjShipp.id

Columns cannot bound in Joins

I am trying to calculate the leaves taken by employee and the addition and deduction in the salary for this month.
I am stuck at this point where I am joining these tables but I am getting error that I can't bound one of the column from table I specified in FROM clause.
Here is my query, If someone can help that'd be appreciated.
SELECT
[EI].[FirstName]+' '+[EI].[LastName] [Employee],
[Addition].[Amount] [AdditionAmount], [AdditionType].[FullName] [AdditionType],
[Deduction].[Amount] [DeductionAmount], [DeductionType].[FullName] [DeductionType],
MONTH([Leave].[ApprovedOn]) AS [Month], Count(*) AS [LeaveTaken]
FROM
[HRM].[tbl_EmployeeSalary] [Salary],
[HRM].[tbl_EmployeeInfo] [EI]
FULL JOIN [HRM].[tbl_EmployeeLeave] [Leave] ON [EI].[ID] = [Leave].[EmpCode]
FULL JOIN [HRM].[tbl_EmployeeSalaryAddition] [Addition] ON [Salary].[ID] = [Addition].[EmpSalaryCode]
FULL JOIN [HRM].[tbl_AdditionType] [AdditionType] ON [AdditionType].[ID] = [Addition].[AdditionTypeCode]
FULL JOIN [HRM].[tbl_EmployeeSalaryDeduction] [Deduction] ON [Salary].[ID] = [Deduction].[EmpSalaryCode]
FULL JOIN [HRM].[tbl_DeductionType] [DeductionType] ON [DeductionType].[ID] = [Deduction].[DeductionTypeCode]
WHERE
MONTH([Leave].[ApprovedOn]) = MONTH(GetDate())
GROUP BY
[EI].[FirstName]+' '+[EI].[LastName],
[Addition].[Amount], [AdditionType].[FullName],
[Deduction].[Amount] , [DeductionType].[FullName],
MONTH([Leave].[ApprovedOn])
I'm pretty much sure there is some sort of syntax issue like the order I am not able to set. I tried searching the issue but can't figure out in my case.
I don't have table structure still this query will remove your syntactical error
SELECT
[EI].[FirstName]+' '+[EI].[LastName] [Employee],
[Addition].[Amount] [AdditionAmount], [AdditionType].[FullName] [AdditionType],
[Deduction].[Amount] [DeductionAmount], [DeductionType].[FullName] [DeductionType],
MONTH([Leave].[ApprovedOn]) AS [Month], Count(*) AS [LeaveTaken]
FROM
[HRM].[tbl_EmployeeInfo] [EI]
FULL JOIN [HRM].[tbl_EmployeeLeave] [Leave]
ON [EI].[ID] = [Leave].[EmpCode],
[HRM].[tbl_EmployeeSalary] [Salary]
FULL JOIN [HRM].[tbl_EmployeeSalaryAddition] [Addition]
ON [Salary].[ID] = [Addition].[EmpSalaryCode]
FULL JOIN [HRM].[tbl_AdditionType] [AdditionType]
ON [AdditionType].[ID] = [Addition].[AdditionTypeCode]
FULL JOIN [HRM].[tbl_EmployeeSalaryDeduction] [Deduction]
ON [Salary].[ID] = [Deduction].[EmpSalaryCode]
FULL JOIN [HRM].[tbl_DeductionType] [DeductionType]
ON [DeductionType].[ID] = [Deduction].[DeductionTypeCode]
WHERE
MONTH([Leave].[ApprovedOn]) = MONTH(GetDate())
GROUP BY
[EI].[FirstName]+' '+[EI].[LastName],
[Addition].[Amount], [AdditionType].[FullName],
[Deduction].[Amount] , [DeductionType].[FullName],
MONTH([Leave].[ApprovedOn])

GROUP BY clause on multiple joins

I need to show Class Wise attendance like this
IN DB i am have separate table (studentattendance) ,which store attendance like this
I Just Need to Show Total students Present Per Class
I try to do Query which give output like this
this is my query
SELECT distinct CM.ClassName ,SB.SubjectName ,(select count(studentattendance.Day1) from studentattendance where day1 = 'P') as Present, convert(varchar(10),AttendanceDate ,126) as AttendancetimeTaken
from studentattendance SA inner join studentmaster SM on SA.StudentID=SM.ID join ProfessorMaster p on SA.ProfessorID =p.Id
join Classmaster CM on SA.ClassID = CM.ID inner join SubjectMaster SB on SA.SubjectID =SB.ID
I need to Group Class Wise . how can I do it
By not having the actual tables, I tried the following modifications, please try it and reply me
SELECT CM.ClassName ,
SB.SubjectName , count(SA.Day1) as Present,
convert(varchar(10),AttendanceDate , 126) as AttendancetimeTaken
from studentattendance SA
inner join studentmaster SM on SA.StudentID=SM.ID
join ProfessorMaster p on SA.ProfessorID =p.Id
join Classmaster CM on SA.ClassID = CM.ID
inner join SubjectMaster SB on SA.SubjectID =SB.ID
where SA.day1 = 'P'
group by CM.ClassName, SB.SubjectName, AttendanceDate

Group by in SQL Server

I have a query in SQL Server
SELECT
k12_dms_contacts_master.prefix_id AS prefix,
k12_dms_contacts_master.first_name,
k12_dms_contacts_master.last_name,
k12_dms_contacts_master.email,
k12_dms_institution_master.inst_name,
k12_dms_institution_master.address,
k12_dms_cities.name AS city_name,
k12_dms_zip_codes.zip_code,
k12_dms_institution_master.type_id,
k12_dms_contacts_institution_jobtitles.glevel_id,
k12_dms_districts.name AS district_name,
k12_dms_counties.name AS county_name,
k12_dms_institution_master.state_id,
k12_dms_institution_master.phone,
k12_dms_contacts_institution_jobtitles.job_title_id
FROM
k12_dms_institution_master
INNER JOIN k12_dms_contacts_institution_jobtitles ON k12_dms_contacts_institution_jobtitles.inst_id = k12_dms_institution_master.id
INNER JOIN k12_dms_contacts_master ON k12_dms_contacts_institution_jobtitles.contact_id = k12_dms_contacts_master.id
INNER JOIN k12_dms_cities ON k12_dms_cities.id = k12_dms_institution_master.city_id
INNER JOIN k12_dms_districts ON k12_dms_districts.id = k12_dms_institution_master.district_id
INNER JOIN k12_dms_counties ON k12_dms_counties.id = k12_dms_institution_master.county_id
INNER JOIN k12_dms_zip_codes ON k12_dms_zip_codes.id = k12_dms_institution_master.zip_code_id
WHERE
k12_dms_zip_codes.zip_code IN ('92678', '92679', '92688', '92690', '92691', '92692', '92693', '92694', '92877',
'92879', '92881', '92883')
ORDER BY
k12_dms_institution_master.state_id,
k12_dms_institution_master.inst_name ASC
Now I want to perform GROUP BY on Email address and Institution name but I am getting this error :
Column 'k12_dms_contacts_master.prefix_id' is invalid in the select
list because it is not contained in either an aggregate function or
the GROUP BY clause.
Any help would be highly appreciable.
The error message says it all.
You have created a group and since this column is not part of the "group by" nor an aggregation of all the groups column (like sum or count) you can't use it in the select clause.
Please note that the return of a group by is one row per group. Logically, that column would be different for any group member so it can not fit one line!

Resources