Joining 4 Tables together and checking where totals do not match - mysql

I have 4 tables act,up, pos_act, pos_up
In this example, let's say I have customer ID and Amount columns as
act.cust_id, up.cust_id, act.amount, up.amount
pos_up.cID, pos_act.cID, pos_up.amount_, pos_act.amount_
act
| cust_id | amount |
|:-------:|:------:|
| 6789 | 30.00 |
| 9876 | 25.00 |
pos_act
| cID | amount_|
|:-------:|:------:|
| 6789 | 30.00 |
| 9876 | 24.99 |
----------------------------------------
up
| cust_id | amount |
|:-------:|:------:|
| 1234 | 10.00 |
| 2345 | 75.00 |
pos_up
| cID | amount_|
|:-------:|:------:|
| 1234 | 9.99 |
| 2345 | 75.00 |
Now With this, I want to compare where amounts do not match all in one table.
So in this example 2345 matches in up but in act 1234 does not match.
Then the results should be
All Unmatched
| cust_id | Table |
|:-------:|:------:|
| 9876 | Act |
| 1234 | Up |
I tried with unions but cant seem to get that working
SELECT *
FROM (
select cID, amount FROM act as a
union select cID, amount FROM up as b
) as v
LEFT JOIN
(select CID, amount_ FROM pos_up as c
UNION select CID, amount_ from pos_act as d
) as r
WHERE a.amount != d.amount_
I also tried with left joins but it just shows me all results. I only want ones that do not match. custid is a unique ID and may appear multiple times.

You just use UNION in a wrong place
SELECT cID, amount, 'act' as `table`
FROM act as a
LEFT JOIN pos_act as pa
ON a.cust_id = pa.
WHERE a.amount != pa.amount_
UNION ALL
SELECT cID, amount, 'up'
FROM up as u
LEFT JOIN pos_up as pu
ON u.cust_id = pu.cID
WHERE u.amount != pu.amount_

Related

How to get hotel total room and booked room in single query

How to get hotel total room and booked room in single query.
I used 2 queries get result. I need this in single query.
The issue I am experiencing since all counts are in this table htl_room_information.id_hotel
Booked room:
SELECT x.hotel_name
, count(i.id_hotel) room
FROM htl_booking_detail d
JOIN htl_branch_info_lang x
ON x.id=d.id_hotel
JOIN htl_room_information i
ON d.id_room=i.id
group
by x.hotel_name;
+------------------------------------------+------+
| hotel_name | room |
+------------------------------------------+------+
| hotel | 3 |
| hotel1 | 1 |
| hotel2 | 4 |
| hotel3 | 13 |
| hotel4 | 9 |
| hotel5 | 3 |
| hotel6 | 3 |
| hotel7 | 2 |
+------------------------------------------+------+
Total Rooms
SELECT (htl_branch_info_lang.hotel_name) as hotel_name,count(htl_room_information.id_hotel) as total_room FROM htl_room_information ,htl_branch_info_lang where htl_room_information.id_hotel=htl_branch_info_lang.id group by htl_branch_info_lang.hotel_name;
+------------------------------------------+------------+
| hotel_name | total_room |
+------------------------------------------+------------+
| hotel | 219 |
| hotel2 | 25 |
| hotel3 | 16 |
| hotel4 | 5 |
| hotel5 | 55 |
| hotel6 | 27 |
| hotel7 | 56 |
| hotel8 | 52 |
+------------------------------------------+------------+
Use dependent subqueries.
SELECT x.hotel_name,
(
SELECT count(i.id_hotel)
FROM htl_booking_detail d
JOIN htl_room_information i
ON d.id_room=i.id
WHERE x.id=d.id_hotel
) as room,
(
SELECT count(i.id_hotel)
FROM htl_room_information i
WHERE i.id_hotel=x.id
) as total_room
FROM htl_branch_info_lang x
I assume that the hotel_name is unique in the htl_branch_info_lang table. If not, you have to put distinct behind the first SELECT.
Hoping, I understood your question correctly.
Please check below query.
select b.hotel_name hotel_name, a.room ,
b.total_room
from
(SELECT htl_branch_info_lang.hotel_name,
count(htl_room_information.id_hotel) as room FROM htl_booking_detail,
htl_branch_info_lang, htl_room_information WHERE
htl_branch_info_lang.id=htl_booking_detail.id_hotel and
htl_booking_detail.id_room=htl_room_information.id group by
htl_branch_info_lang.hotel_name ) a RIGHT join (SELECT (htl_branch_info_lang.hotel_name) as
hotel_name,count(htl_room_information.id_hotel) as total_room
FROM htl_room_information ,htl_branch_info_lang
where htl_room_information.id_hotel=htl_branch_info_lang.id
group by htl_branch_info_lang.hotel_name) b
on a.hotel_name = b.hotel_name
;
You can use subquery
try this:
SELECT (a.hotel_name) as
hotel_name,count(htl_room_information.id_hotel) as total_room, (SELECT
count(htl_room_information.id_hotel) as room FROM htl_booking_detail,
htl_branch_info_lang b, htl_room_information WHERE
b.id=htl_booking_detail.id_hotel and
htl_booking_detail.id_room=htl_room_information.id and
b.hotel_name = a.hotel_name), count(htl_room_information.id_hotel) - (SELECT
count(htl_room_information.id_hotel) as room FROM htl_booking_detail,
htl_branch_info_lang b, htl_room_information WHERE
b.id=htl_booking_detail.id_hotel and
htl_booking_detail.id_room=htl_room_information.id and
b.hotel_name = a.hotel_name) as available FROM htl_room_information
,htl_branch_info_lang
a where htl_room_information.id_hotel=a.id group by
a.hotel_name;

Multiple rows with same identifier, how to select the row with heighest value (ignoring the rest) with multiple left joins?

this issue has been bothering me for a few hours now. After finding out my old query had an issue, I had to rebuild it.
The situation:
I need to match each patient_id with a clinic_id, and for that I get all the appointments using the patient_id,
find the highest appointment_id and use its clinic_id to set the last known clinic_id.
My old query did this, but it skipped patients that never had an appointment.
These are my current results, but I need to filter my results. Question is, how?
+---------------+-------------------+-------------------+---------------+
| patient_id | country_code | appointment_id | clinic_id |
+---------------+-------------------+-------------------+---------------+
| 111 | UK | 620 | 3 |
| 111 | UK | 621 | 2 |
| 111 | UK | 1995 | 1 |
| 222 | UK | 609 | 3 |
| 222 | UK | 610 | 2 |
| 333 | UK | null | null |
| 444 | UK | null | null |
+---------------+-------------------+-------------------+---------------+
What I want is the following:
+---------------+-------------------+-------------------+---------------+
| patient_id | country_code | appointment_id | clinic_id |
+---------------+-------------------+-------------------+---------------+
| 111 | UK | 1995 | 1 |
| 222 | UK | 610 | 2 |
| 333 | UK | null | null |
| 444 | UK | null | null |
+---------------+-------------------+-------------------+---------------+
I am using the following query right now:
SELECT
patient.id,
systemcountry.country_code,
appointment_patient.appointment_id,
appointment.clinic_id
FROM
patient
LEFT JOIN
systemcountry ON patient.country_id = systemcountry.id
LEFT JOIN
appointment_patient ON patient_id = patient.id
LEFT JOIN
appointment ON appointment_patient.appointment_id = appointment.id
This was my old query, which had an issue causing it to skip patients that never had an appointment:
SELECT
patient.id AS patient_id,
systemcountry.code AS systemcountry_code,
appointment.clinic_id
FROM
patient
LEFT JOIN
systemcountry ON patient.land_id = systemcountry.id,
appointment
WHERE
appointment.id = (SELECT
MAX(appointment_id)
FROM
appointment_patient
WHERE
patient_id = patient.id);
I am still a beginner, so go easy on me.
I appreciate any input, thanks!
Move the sub-select in your original query's WHERE clause into a LEFT JOIN (something like this):
LEFT JOIN
(SELECT MAX(appointment_id), patient_id
FROM appointment_patient
GROUP BY patient_id) as apt ON patient.patient_id=apt.patient_id
You can try function max() over columns whose only highest value you want, then group by the result set using patient.id
SELECT
patient.id,
systemcountry.country_code,
max(appointment_patient.appointment_id),
appointment.clinic_id
FROM
patient
LEFT JOIN
systemcountry ON patient.country_id = systemcountry.id
LEFT JOIN
appointment_patient ON patient_id = patient.id
LEFT JOIN
appointment ON appointment_patient.appointment_id = appointment.id
GROUP BY patient.id

How to select the sum() of a group of rows and the sum() of another group

I have created a SQLfiddle demo with sample data and desired result here :(http://sqlfiddle.com/#!9/dfe73a/7)
sample data
-- table company
+--------+---------+
| id | name |
+--------+---------+
| 1 | foo |
| 2 | bar |
+--------+---------+
-- table sales
+--------+---------------+-----------------+
| id | company_id | total_amount |
+--------+---------------+-----------------+
| 1 | 1 | 300.0 |
| 2 | 1 | 300.0 |
| 2 | 1 | 100.0 |
+--------+---------------+-----------------+
-- table moves
+--------+---------------+-----------------+
| id | company_id | balance_move |
+--------+---------------+-----------------+
| 1 | 1 | 700.0 |
| 2 | 1 | -300.0 |
| 2 | 1 | -300.0 |
+--------+---------------+-----------------+
I need to select every company along with the sum of it's total amount of sales and the sum of it's total balance moves
desired result
+----+----------------------+---------------------+
| id | total_amount_sum | balance_move_sum |
+----+----------------------+---------------------+
| 1 | 700 | 100 |
+----+----------------------+---------------------+
| 2 | (null) | (null) |
+----+----------------------+---------------------+
I tried this SQL query
SELECT
company.id,
sum(total_amount) total_amount_sum,
sum(balance_move) balance_move_sum
FROM company
LEFT JOIN sales ON company.id = sales.company_id
LEFT JOIN moves ON company.id = moves.company_id
GROUP BY company.id
But the sum() functions add all the redundant values came from the joins which result in 2100 (700*3) for total amount and 300 (100*3) for net balance
bad SQL statement result
+----+----------------------+---------------------+
| id | total_amount_sum | balance_move_sum |
+----+----------------------+---------------------+
| 1 | 2100 | 300 |
+----+----------------------+---------------------+
| 2 | (null) | (null) |
+----+----------------------+---------------------+
Is it possible to achieve the result I want ?
You're repeating rows by doing your joins.
Company: 1 row per company
After Sales join: 3 rows per company (1x3)
After Moves join: 9 rows per company (3x3)
You end up triplicating your SUM because of this.
One way to fix is to use derived tables like this, which calculate the SUM first, then join the resulting rows 1-to-1.
SELECT
company.id,
total_amount_sum,
balance_move_sum
FROM company
LEFT JOIN (SELECT SUM(total_amount) total_amount_sum, company_id
FROM sales
GROUP BY company_id
) sales ON company.id = sales.company_id
LEFT JOIN (SELECT SUM(balance_move) balance_move_sum, company_id
FROM moves
GROUP BY company_id
) moves ON company.id = moves.company_id
Using sub-queries to calculate the two sums separately will work.
SELECT
company.id,
(Select sum(total_amount) from sales where sales.company_id = company.id) total_amount_sum,
(Select sum(balance_move) from moves where moves.company_id = company.id) balance_move_sum
FROM company

MySQL select unique rows in two columns with the highest value in one column

I have a basic table:
+-----+--------+------+------+
| id, | name, | cat, | time |
+-----+--------+------+------+
| 1 | jamie | 1 | 100 |
| 2 | jamie | 2 | 100 |
| 3 | jamie | 1 | 50 |
| 4 | jamie | 2 | 150 |
| 5 | bob | 1 | 100 |
| 6 | tim | 1 | 300 |
| 7 | alice | 4 | 100 |
+-----+--------+------+------+
I tried using the "Left Joining with self, tweaking join conditions and filters" part of this answer: SQL Select only rows with Max Value on a Column but some reason when there are records with a value of 0 it breaks, and it also doesn't return every unique answer for some reason.
When doing the query on this table I'd like to receive the following values:
+-----+--------+------+------+
| id, | name, | cat, | time |
+-----+--------+------+------+
| 1 | jamie | 1 | 100 |
| 4 | jamie | 2 | 150 |
| 5 | bob | 1 | 100 |
| 6 | tim | 1 | 300 |
| 7 | alice | 4 | 100 |
+-----+--------+------+------+
Because they are unique on name and cat and have the highest time value.
The query I adapted from the answer above is:
SELECT a.name, a.cat, a.id, a.time
FROM data A
INNER JOIN (
SELECT name, cat, id, MAX(time) as time
FROM data
WHERE extra_column = 1
GROUP BY name, cat
) b ON a.id = b.id AND a.time = b.time
The issue here is that ID is unique per row you can't get the unique value when getting the max; you have to join on the grouped values instead.
SELECT a.name, a.cat, a.id, a.time
FROM data A
INNER JOIN (
SELECT name, cat, MAX(time) as time
FROM data
WHERE extra_column = 1
GROUP BY name, cat
) b ON A.Cat = B.cat and A.Name = B.Name AND a.time = b.time
Think about it... So what ID is mySQL returning form the Inline view? It could be 1 or 3 and 2 or 4 for jamie. Hows does the engine know to pick the one with the max ID? it is "free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. " it could pick the wrong one resulting in incorrect results. So you can't use it to join on.
https://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html
If you want to use a self join, you could use this query:
SELECT
d1.*
FROM
date d1 LEFT JOIN date d2
ON d1.name=d2.name
AND d1.cat=d2.cat
AND d1.time<d2.time
WHERE
d2.time IS NULL
It is very simple
SELECT MAX(TIME),name,cat FROM table name group by cat

How to write queries to calculate today's due amount?

I have scheduled payments, so I have these tables:
customer
+id
paymentSchedule
+id
+customer_id
+amount //total price
+dueDate //date to be paid
payments
+id
+date
+customer_id
+paymentSchedule_id
+amount //amount paid, it can be a partial payment
How do I write a query to get Today's due amount by customer.
I mean I need to join the tables (thats my main problem) and then substract the
sum of the payments.mount minus the sum of the scheduledPaymens.amount
but.. how?
Thanks in advance
This is probably not 100%, but should be pretty solid to help you tweak:
SELECT customer_id, (due.amount - paid.amount) as amountDue
FROM
(SELECT customer_id, SUM(amount) as amount
FROM paymentSchedule
WHERE dateDate <= getDate()
and customer_id = #custid) as due
LEFT JOIN
(SELECT customer_id, SUM(amount) as amount
FROM payments
WHERE customer_id = #custid) as paid ON paid.customer_id = due.customer_id
Ok, this is how I understood the problem. I simplified the tables because they where just complicating things, and adding dates is just straight forward.
PaymentSchedule
+----+-------------+-----------------+
| id | customer_id | original_amount |
+----+-------------+-----------------+
| 1 | Tom | 100 |
| 2 | Tom | 200 |
| 3 | Tom | 300 |
| 4 | Moe | 400 |
+----+-------------+-----------------+
Payments
+----+--------------------+-------------+
| id | paymentSchedule_id | paid_amount |
+----+--------------------+-------------+
| 1 | 1 | 70 |
| 2 | 2 | 150 |
| 3 | 2 | 50 |
| 4 | 4 | 300 |
| 5 | 4 | 25 |
+----+--------------------+-------------+
Result of query
+-------------+-------------------+-----------------+-----------+----------------+
| CUSTOMER_ID | PAYMENTSCHEDULEID | ORIGINAL_AMOUNT | TOTALPAID | PENDINGPAYMENT |
+-------------+-------------------+-----------------+-----------+----------------+
| Tom | 1 | 100 | 70 | 30 |
| Tom | 2 | 200 | 200 | 0 |
| Tom | 3 | 300 | 0 | 300 |
| Moe | 4 | 400 | 325 | 75 |
+-------------+-------------------+-----------------+-----------+----------------+
Query with double select
select *, s.original_amount - s.TotalPaid as PendingPayment from (
select
ps.customer_id, ps.id as PaymentScheduleId, ps.original_amount,
coalesce(sum(p.paid_amount), 0) as TotalPaid
from paymentSchedule ps
left join payments p on p.paymentSchedule_id = ps.id
group by ps.customer_id, PaymentScheduleId, ps.original_amount
) as S
Query with single select
select
ps.customer_id, ps.id as PaymentScheduleId, ps.original_amount,
coalesce(sum(p.paid_amount), 0) as TotalPaid,
ps.original_amount - coalesce(sum(p.paid_amount), 0) as PendingPayment
from paymentSchedule ps
left join payments p on p.paymentSchedule_id = ps.id
group by ps.customer_id, PaymentScheduleId, ps.original_amount
The result of both queries is the same. I just wonder which one runs faster. You can try both and tell us :)
Let me know if this this is the result you expected
Something like this should be a good starting point for you to tweak.
SELECT c.*
FROM customer c
INNER JOIN paymentSchedule ps
ON c.id = ps.customer_id
LEFT JOIN payments p
ON ps.id = p.paymentSchedule_id
WHERE ps.dueDate = 'This depends on how you store dueDate'
AND ps.amount - p.amount > 0