sum column not working properly with sub query - mysql

i have some code to mysql query, but it's not showing right result.
This is my code:
select a.spent
, t_rinci.harga as price
from t_pengajuan
join t_rinci
on t_rinci.id_pengajuan = t_pengajuan.id
left
JOIN
( SELECT t_realisasi.id_rinci as id
, SUM(nilai_realisasi) spent
FROM t_realisasi
GROUP
by id ) a
on a.id = t_rinci.id_rinci
where t_rinci.id_rinci in (a.id)
group
by t_rinci.id_pengajuan
expected result is
spent
price
400000
4250000
1000000
1100000
but it say
spent
price
400000
4250000
1000000
1000000
here my sqlfiddle

Here's an example of a coherent query:
select r.id_pengajuan
, SUM(a.spent) spent
, SUM(r.harga) as price
from t_pengajuan p
join t_rinci r
on r.id_pengajuan = p.id
JOIN
( SELECT t_realisasi.id_rinci as id
, SUM(nilai_realisasi) spent
FROM t_realisasi
GROUP
by id ) a
on a.id = r.id_rinci
group
by r.id_pengajuan
It might not be what you're after, but it does at least make sense.

Related

How to use the SELECT clause twice in a sql statement

I want to have a table where I can view today's balance as well as yesterday's balance as two different column. Is there any way I can select from two different dates?
Below is the SQL statement I have tried however I am not able to see the yesterday balance.
(SELECT food.food_id, food.food_name, food.food_chi_name, food.food_category, food.chinesechar, SUM(inventory.tmr_input+inventory.final_balance), SUM(inventory.balance), SUM(inventory.input), SUM(inventory.reject), SUM(inventory.final_balance), SUM(inventory.tmr_input), SUM(inventory.sale), SUM(inventory.theoritical), SUM(inventory.yest_theoritical), SUM(inventory.3PMsale), SUM(inventory.3PMbalance), SUM(inventory.wholesale) FROM inventory INNER JOIN food ON inventory.food_id=food.food_id WHERE food.outlet = 'T11' AND inventory.date = '04/30/2021' GROUP BY food.food_id ORDER BY food.food_id ASC); (SELECT SUM(inventory.balance) as yesterday_balance FROM inventory INNER JOIN food ON inventory.food_id=food.food_id WHERE food.outlet = 'T11' AND inventory.date = '04/29/2021' GROUP BY food.food_id ORDER BY food.food_id ASC);
You can use a subselect for that purpose
And using aliases helps to get a better overview
SELECT
f1.food_id
, f1.food_name
, f1.food_chi_name
, f1.food_category
, f1.chinesechar
, SUM(i1.tmr_input+i1.final_balance)
, SUM(i1.balance)
, SUM(i1.input)
, SUM(i1.reject)
,SUM(i1.final_balance)
, SUM(i1.tmr_input)
, SUM(i1.sale)
, SUM(i1.theoritical)
, SUM(i1.yest_theoritical)
, SUM(i1.`3PMsale`)
, SUM(i1.`3PMbalance`)
, SUM(i1.wholesale)
,(SELECT SUM(i2.balance)
FROM
inventory i2 INNER JOIN food f2 ON i2.food_id=f2.food_id
WHERE f2.outlet = 'T11' AND i2.date = '04/29/2021'
AND f2.food_id = f1.food_id
) as yesterday_balance
FROM
inventory i1
INNER JOIN
food f1 ON i1.food_id=f1.food_id
WHERE
f1.outlet = 'T11'
AND i1.date = '04/30/2021'
GROUP BY f1.food_id
ORDER BY f1.food_id ASC;

AVG join result in other table

I've got a query with avg results. In another table I have the results of that
avg result in text.
Right now this is my query:
select round(avg(breed_ratings.rating)) as result, breed_ratings.score_name, count(*) as total, breeds.name_en
from breed_ratings
inner join breeds on breeds.id = breed_ratings.breed_id
where breeds.id = 188
group by score_name, breeds.name_en
The rating_result table looks like this:
id
rating
result_text
How can I get the result_text in this query?
Please help me out.
--EDIT
I need to get the result from the image below in text.
So I have another table where this is stored I need to get the result_nl where it matches the rating:
Desired result (if rating is 5):
result: 5
score_name: ADULT_FRIENDLY
total: 117
name_en: American Staffordshire Terrier
result_nl: I am extremely dominant
I think you want to join the average to the first rating in rating_results where the average is bigger than the listed rating there. If so:
select br.*, rr.result_text
from (select round(avg(br.rating)) as result, br.score_name, count(*) as total, b.name_en
from breed_ratings br join
breeds b
on b.id = br.breed_id
where b.id = 188
group by br.score_name, b.name_en
) br left join
(select rr.*, lead(rr.rating) over (order by rr.rating) as next_rating
from rating_result rr
) rr
on br.result >= rr.rating and
(br.result < rr.next_rating or rr.next_rating is null)

joint three tables in Mysql

I have three tables employee, promotion and punishment
Employee’s table structure something like this
Id int
Fullname varchar
...............
promotionDate date
Promotion’s table structure is like this
id int
emp_id int
directorateDate date
And punishment’s table structure is like this
id int
emp_id int
direcotorateDate date
Let’s say employee table has 200 records, each month a group of employees have promotion (after serving one year), I want to get the list of all employees in the current month that get promotion
I can easily get the list by this query
SELECT *
FROM employee
WHERE MONTH(promotionDate) = MONTH(CURRENT_DATE())
AND YEAR(promotionDate) = YEAR(CURRENT_DATE())
My question is
I want to count number of punishments and promotions each employee got in the current year from punishment and promotion table respectively
I did this query but it did not get right results
SELECT e.fullname , COUNT(punish.emp_id) as siza ,COUNT(pro.emp_id) as supas
FROM emp_employee as e
LEFT JOIN emp_punishment as punish on punish.emp_id=e.id
LEFT JOIN emp_promotion as pro on e.id=pro.emp_id
WHERE ((MONTH(e.promotionDate) = MONTH(CURRENT_DATE())
AND YEAR(e.promotionDate) = YEAR(CURRENT_DATE()))
AND ( YEAR(punish.directorate_date) = YEAR(CURRENT_DATE()) )
AND ( YEAR(pro.directorate_date) = YEAR(CURRENT_DATE()) )
GROUP BY e.fullname;
Any help please.
By joining directly the 3 tables you get duplicate rows.
Group by emp_id and aggregate separately each of the tables emp_punishment and emp_promotion and join the results to the table emp_employee.
select e.fullname, coalesce(pu.siza, 0) siza, coalesce(pr.supas, 0) supas
from emp_employee as e
left join (
select emp_id, count(*) siza
from emp_punishment
where year(directorate_date) = year(CURRENT_DATE)
group by emp_id
) pu on pu.emp_id = e.id
left join (
select emp_id, count(*) supas
from emp_promotion
where year(directorate_date) = year(CURRENT_DATE)
group by emp_id
) pr on pr.emp_id = e.id
I used only the condition:
where year(directorate_date) = year(CURRENT_DATE())
because in your question you say:
I want to count number of punishments and promotions each employee got in the current year from punishment and promotion
Removing MONTH() function, and moving each condition to their respective place, instead of within the WHERE clause should resolve the issue (Since, they're considered as if INNER JOINs with the current style ).
Only keep common column e.promotionDate within the WHERE clause :
SELECT e.fullname,
COUNT(punish.emp_id) as siza ,
COUNT(pro.emp_id) as supas
FROM emp_employee as e
LEFT JOIN emp_punishment as punish
ON punish.emp_id=e.id
AND YEAR(punish.directorate_date) = YEAR(CURRENT_DATE())
LEFT JOIN emp_promotion as pro
ON e.id=pro.emp_id
AND YEAR(pro.directorate_date) = YEAR(CURRENT_DATE()))
WHERE YEAR(e.promotionDate) = YEAR(CURRENT_DATE())
GROUP BY e.fullname;

MySQL Multiple Join Query with Limit on One Join

I have a MYSQL query I'm working on that pulls data from multiple joins.
select students.studentID, students.firstName, students.lastName, userAccounts.userID, userstudentrelationship.userID, userstudentrelationship.studentID, userAccounts.getTexts, reports.pupID, contacts.pfirstName, contacts.plastName, reports.timestamp
from userstudentrelationship
join userAccounts on (userstudentrelationship.userID = userAccounts.userID)
join students on (userstudentrelationship.studentID = students.studentID)
join reports on (students.studentID = reports.studentID)
join contacts on (reports.pupID = contacts.pupID)
where userstudentrelationship.studentID = "10000005" AND userAccounts.getTexts = 1 ORDER BY reports.timestamp DESC LIMIT 1
I have a unique situation where I would like one of the joins (the reports join) to be limited to the latest result only for that table (order by reports.timestamp desc limit 1 is what I use), while not limiting the result quantities for the overall query.
By running the above query I get the data I would expect, but only one record when it should return several.
My question:
How can I modify this query to ensure that I receive all possible records available, while ensuring that only the latest record from the reports join used? I expect that each record will possibly contain different data from the other joins, but all records returned by this query will share the same report record
Provided I understand the issue; one could add a join to a set of data (aliased Z below) that has the max timestamp for each student; thereby limiting to one report record (most recent) for each student.
SELECT students.studentID
, students.firstName
, students.lastName
, userAccounts.userID
, userstudentrelationship.userID
, userstudentrelationship.studentID
, userAccounts.getTexts
, reports.pupID
, contacts.pfirstName
, contacts.plastName
, reports.timestamp
FROM userstudentrelationship
join userAccounts
on userstudentrelationship.userID = userAccounts.userID
join students
on userstudentrelationship.studentID = students.studentID
join reports
on students.studentID = reports.studentID
join contacts
on reports.pupID = contacts.pupID
join (SELECT max(timestamp) mts, studentID
FROM REPORTS
GROUP BY StudentID) Z
on reports.studentID = Z.studentID
and reports.timestamp = Z.mts
WHERE userstudentrelationship.studentID = "10000005"
AND userAccounts.getTexts = 1
ORDER BY reports.timestamp
for get all the records you should avoid limit 1 at the end of the query
for join anly one row from reports table you could use subquery as
select
students.studentID
, students.firstName
, students.lastName
, userAccounts.userID
, userstudentrelationship.userID
, userstudentrelationship.studentID
, userAccounts.getTexts
, t.pupID
, contacts.pfirstName
, contacts.plastName
, t.timestamp
from userstudentrelationship
join userAccounts on userstudentrelationship.userID = userAccounts.userID
join students on userstudentrelationship.studentID = students.studentID
join (
select * from reports
order by reports.timestamp limit 1
) t on students.studentID = t.studentID
join contacts on reports.pupID = contacts.pupID
where userstudentrelationship.studentID = "10000005"
AND userAccounts.getTexts = 1

Issue with Mysql SUM and GROUP_CONCAT in query

I am having issue with my query having both SUM and GROUP_CONCAT function.
The sum values changes as GROUP_CONCAT values increases.
Below is my code:
SELECT ul.display_name,
ul.photo,
ul.user_id,
Sum(ulr.level_score) AS level_scores,
Sum(ulr.level_timer) AS level_timer,
Group_concat(ulr.level_completed) AS levels,
Group_concat(DISTINCT c.bit_id) AS bit_id
FROM user_level_responses AS ulr
INNER JOIN user_login AS ul
ON (
ul.user_id=ulr.user_id)
INNER JOIN c_member AS cm
ON (
cm.user_id=ul.user_id
AND cm.user_approval='Y'
AND cm.delete_status='0'
AND cm.status='1')
INNER JOIN ctree ct
ON (
cm.circuit_id=ct.circuit_id )
INNER JOIN cir AS c
ON (
c.circuits_id=cm.circuit_id
AND c.builtin=0
AND c.delete_status='0'
AND c.status='1')
WHERE Match(ct.circuit_path) against ('_902_')
AND ulr.institution_id=321
AND ulr.delete_status=0
AND ulr.status=1
AND ul.delete_status=0
GROUP BY ulr.user_id
ORDER BY level_scores DESC,
level_timer ASC,
ul.display_name limit 500
If the actual score is 900 and if i have 2 ids in GROUP_CONCAT then actual score is double the original.
Expected OUTPUT:
user1 2010.cs,btech 960 00:01:08 Completed
user2 btech 920 00:01:08 Completed
OUTPUT GETTING:
user1 2010.cs,btech 1920 00:01:08 Completed
user2 btech 920 00:01:08 Completed
twice the actual amount ie 960.
Your problem is that your multiple ids are doubling the rows that your result has before the grouping. You can solve this problem by joining in all of the external data in a subquery.
I have absolutely no idea the structure of your database, nor all of the functions, but this is a stab in the dark at reorganizing your query. If you need, I can write up a much simpler SQLFiddle to show you what I mean.
SELECT ul2.display_name,
ul2.photo,
ul2.user_id,
Sum(ulr.level_score) AS level_scores,
Sum(ulr.level_timer) AS level_timer,
Group_concat(ulr.level_completed) AS levels,
ul2.bit_id
FROM user_level_responses AS ulr
INNER JOIN (
SELECT
ul.display_name,
ul.photo,
ul.user_id,
GROUP_CONTACT(DISTINCT c.bit_id) as bit_id
FROM user_login AS ul
INNER JOIN c_member AS cm
ON (
cm.user_id=ul.user_id
AND cm.user_approval='Y'
AND cm.delete_status='0'
AND cm.status='1')
INNER JOIN ctree ct
ON (
cm.circuit_id=ct.circuit_id )
INNER JOIN cir AS c
ON (
c.circuits_id=cm.circuit_id
AND c.builtin=0
AND c.delete_status='0'
AND c.status='1')
WHERE Match(ct.circuit_path) against ('_902_')
AND ul.delete_status=0
GROUP BY ul.user_id
) AS ul2
ON (
ulr.user_id = ul2.user_id )
WHERE ulr.institution_id=321
AND ulr.delete_status=0
AND ulr.status=1
GROUP BY ulr.user_id
ORDER BY level_scores DESC,
level_timer ASC,
ul.display_name limit 500