Sum of columns using join - mysql

SELECT
td.EstimatedTotalAmount_Car,
AVG(tdca.EstimatedTotalAmount) AS policy_saving
FROM Company_Reporting td
INNER JOIN Company_Car_Archive tdca
ON tdca.VehClassSize = td.VehClassSize_Car
AND tdca.VendorName != td.VendorName_Car
AND tdca.USER_SEARCH_ID = td.SEARCH_ID_Car
WHERE td.Company_id = 12
AND td.CHECKOUT_STS = 1
AND td.Check_Type = 3
AND td.policy_violate_flag = 0
GROUP BY td.ID
Above SQL is returning the below output.
EstimatedTotalAmount_Car policy_saving
55.86 75.197856
55.86 75.197856
170.83 244.070000
143.66 132.120000
171.96 131.007272
222.66 226.162725
97.03 79.554001
56.61 74.213999
But I want the sum of both columns in the single record.
sum(EstimatedTotalAmount_Car): 974.47 sum(policy_saving):1037.523709
How can I achieve this?

You can do this in outer query like
select sum(EstimatedTotalAmount_Car),
sum(policy_saving)
from(
/** your query */
) t

Just wrap your current query and sum both columns:
SELECT
SUM(EstimatedTotalAmount_Car) AS grand_total,
SUM(policy_saving) AS sum_policy_saving
FROM
(
SELECT
td.EstimatedTotalAmount_Car,
AVG(tdca.EstimatedTotalAmount) AS policy_saving
FROM Company_Reporting td
INNER JOIN Company_Car_Archive tdca
ON tdca.VehClassSize = td.VehClassSize_Car AND
tdca.VendorName != td.VendorName_Car AND
tdca.USER_SEARCH_ID = td.SEARCH_ID_Car
WHERE
td.Company_id = 12 AND
td.CHECKOUT_STS = 1 AND
tgd.Check_Type = 3 AND
td.policy_violate_flag = 0
GROUP BY td.ID
) t;

Related

SQL - Divide One Query by Another

I am trying to create a query which returns the workout percentage completion...
Workout Percentage Completion =
((Sum of LogEntries WHERE date = IN list of dates and WorkoutID =1 ) /
(Sum of all set numbers WHERE WorkoutID = 1))
x 100
Below is what I currently have, at the moment it is only returning the result of the first query.
What should I change for the query to run correctly?
SELECT
(
(
SELECT COUNT(LogEntriesID)
FROM LogEntriesTable
LEFT JOIN ExerciseWorkoutJunctionTable
ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
LogEntriesTable.JunctionID
WHERE LogEntriesTable.date IN (
"14-05-2020", "15-05-2020", "16-05-2020", "17-05-2020",
"18-05-2020", "19-05-2020", "20-05-2020"
)
AND ExerciseWorkoutJunctionTable.WorkoutID = 1
) / (
SELECT sum(SetNumber)
FROM ExerciseWorkoutGoalsTable
LEFT JOIN ExerciseWorkoutJunctionTable
ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
ExerciseWorkoutGoalsTable.JunctionID
WHERE ExerciseWorkoutJunctionTable.WorkoutID = 1
)
)
Your first SELECT statement is doing an OUTER JOIN but then you have a WHERE clause that is selecting non-NULL values from the ExerciseWorkoutJunctionTable table, so I suspect you might as well be doing an INNER JOIN.
When you have two queries, try:
SET #sum = (SELECT SUM(SetNumber) etc ....);
SELECT (COUNT(LogEntriesID) * 100 / #sum) AS percentage
FROM etc.
If you are using MySQL >= 8.0 you should be able to use window functions like this which breakdown your query into more readable sections.
with entries as (
SELECT COUNT(LogEntriesID) as log_entry_count
FROM LogEntriesTable as l
LEFT JOIN ExerciseWorkoutJunctionTable as e ON
e.ExerciseWorkoutJunctionID = l.JunctionID
WHERE l.date IN ("14-05-2020","15-05-2020","16-05-2020","17-05-2020","18-05-2020","19-05-2020","20-05-2020")
AND e.WorkoutID = 1
),
sets as (
SELECT sum(SetNumber) as set_sum
FROM ExerciseWorkoutGoalsTable as eg
LEFT JOIN ExerciseWorkoutJunctionTable ej
ON ej.ExerciseWorkoutJunctionID = eg.JunctionID
WHERE ej.WorkoutID = 1
)
select ((select log_entry_count from entries) / (select set_sum from sets)) * 100 as workout_completion_pct

Counting entry in a column MySQL and display counts

I would want to count entries in a column and display the count beside it.
However, I'm clueless on how can I do it.
Desired output:
arrangement_number tray_no rl_type flag(count of occurrence)
------------------ ------- ---- ----
2774818 381001 R 3
2774818 381001 R 3
2774818 381001 L 3
2778470 405128 R 1
2779702 265265 R 2
2779702 265265 R 2
I'm currently trying queries using #variables but I still cant get it right.
each row are unique and I need them not to be grouped.
Update: Expanded Table added source code
Note: I'm currently joining 5 tables now
Actual Query:
SELECT
log.arrangement_number,
header.tray_number,
detail.rl_type,
-- some more fields here
FROM
log
INNER JOIN
header ON log.arrangement_number = header.rxarrangement_number
AND log.production_place_code = header.production_place_code
INNER JOIN
detail ON log.arrangement_number = detail.rxarrangement_number
AND log.production_place_code = detail.production_place_code
INNER JOIN
deliveryperiod ON log.arrangement_number = deliveryperiod.arrangement_number
AND log.production_place_code = deliveryperiod.production_place_code
AND detail.rl_type = deliveryperiod.rl_type
INNER JOIN
calc ON calc.arrangement_number = log.arrangement_number
AND calc.production_place_code = log.production_place_code
AND deliveryperiod.rl_type = calc.rl_type
AND detail.rl_type = calc.rl_type
WHERE
header.status_code IN ('20' , '21')
AND log.process_code = '12'
AND deliveryperiod.process_code_current = '12'
AND deliveryperiod.sub_process_code_current IN ('100' , '105')
AND lot_number = '120131'
ORDER BY log.lot_number , log.sequence_number , deliveryperiod.rl_type DESC
SELECT t1.tray_no,
t2.flag
FROM yourTable
INNER JOIN
(
SELECT tray_no, COUNT(*) AS flag
FROM yourTable
GROUP BY tray_no
) t2
ON t1.tray_no = t2.tray_no
try this...
SELECT tray_no, COUNT(*) 'flag'
FROM table1
GROUP BY tray_no

Inner join returning more results even after excluding parameters

My actuall query is:
SELECT rrr.extern_OD_id,
rrr.refund_it_amount,
rrr.refund_amount,
rrr.invoice_ref_7,
rrr.invoice_total_amount
FROM
(SELECT return.extern_OD_id,
return.refund_it_amt AS refund_it_Amount,
return.refund_amount,
billing_tbl.invoice_ref_7,
billing_tbl.invoice_total_amount
FROM
(SELECT rrrf.extern_OD_id,
sum(rrrf.refund_it_amt) AS refund_it_amt,
sum(rrrf.refund_amount/100) refund_amount
FROM rrr__refunds_fact rrrf
WHERE rrrf.refund_status = 'completed'
AND rrrf.refund_created_date_key >= '20150401'
AND rrrf.refund_mode IN('CREDIT_CARD',
'CREDIT_EMI',
'DDCHEQUE',
'DEBIT_CARD',
'GIFT_VOUCHER',
'ICICI',
'NETBANKING',
'back_to_source')
AND rrrf.refund_mode NOT IN ('GIFT_Card')
GROUP BY rrrf.extern_OD_id) RETURN
LEFT JOIN
(SELECT invoice_ref_7,
sum(invoice_total_amount) invoice_total_amount
FROM invoice_fact
WHERE invoice_type_key = 'receiv_note'
AND invoice_status_key NOT IN('voided',
'canceled',
'cancelled')
GROUP BY invoice_ref_7) billing_tbl ON RETURN.extern_OD_id =billing_tbl.invoice_ref_7
WHERE RETURN.refund_amount <> billing_tbl.invoice_total_amount
OR billing_tbl.invoice_ref_7 IS NULL) rrr
WHERE rrr.refund_it_amount >0
AND rrr.refund_amount >0
But when I try to join another table and exclude some parameters, it gives me more records than records from table srrr__refunds_fact.
It gives many records from the new joined table i.e. Payment_TBL which are not present in rrr__refunds_fact.
Can you please tell me where I am going wrong.
As per my understanding if the first query is returning n records, after joining the new records should be n or < n
SELECT rrr.extern_OD_id,
rrr.refund_it_amount,
rrr.refund_amount,
rrr.invoice_ref_7,
rrr.invoice_total_amount
FROM
(SELECT return.extern_OD_id,
return.refund_it_amt AS refund_it_Amount,
return.refund_amount,
billing_tbl.invoice_ref_7,
billing_tbl.invoice_total_amount
FROM
(SELECT rrrf.extern_OD_id,
sum(rrrf.refund_it_amt) AS refund_it_amt,
sum(rrrf.refund_amount/100) refund_amount
FROM rrr__refunds_fact rrrf
JOIN Payment_TBL paymt ON paymt.payment_ref_num_2 = rrrf.extern_OD_id
WHERE rrrf.refund_status = 'completed'
AND rrrf.refund_created_date_key >= '20150401'
AND rrrf.refund_mode IN('CREDIT_CARD',
'CREDIT_EMI',
'DDCHEQUE',
'DEBIT_CARD',
'GIFT_VOUCHER',
'ICICI',
'NETBANKING',
'back_to_source')
AND rrrf.refund_mode NOT IN ('GIFT_Card')
AND paymt.payment_method_key NOT IN ('WALLET')
AND paymt.payment_ref_num_4 NOT IN ('PRICE_REFUND')
GROUP BY rrrf.extern_OD_id) RETURN
LEFT JOIN
(SELECT invoice_ref_7,
sum(invoice_total_amount) invoice_total_amount
FROM invoice_fact
WHERE invoice_type_key = 'receiv_note'
AND invoice_status_key NOT IN('voided',
'canceled',
'cancelled')
GROUP BY invoice_ref_7) billing_tbl ON RETURN.extern_OD_id =billing_tbl.invoice_ref_7
WHERE RETURN.refund_amount <> billing_tbl.invoice_total_amount
OR billing_tbl.invoice_ref_7 IS NULL) rrr
WHERE rrr.refund_it_amount >0
AND rrr.refund_amount >0

How to modify my query for the below requirement?

This is the query where I can the order_seq_num as 2 but I want to get value from the column test_group_id from the t_patient_mhc_step_group_mapping for selected order_seq_num if the order_seq_num selected the row value 2 in t_patient_mhc_step_mapping.
SELECT
IF((labrep.lab_status_id = 2
&& labrep.mhc_status = 'MHC'),
MIN(stepmap.order_seq_num) + 1,
MIN(stepmap.order_seq_num)) AS step_order_seq_num
FROM
`t_patient_mhc_step_group_mapping` stepgroup
INNER JOIN
t_patient_mhc_step_mapping stepmap ON stepgroup.step_id = stepmap.step_id
AND stepmap.mhc_step_status = 1
INNER JOIN
`t_patient_mhc_mapping` mhcmap
INNER JOIN
`t_lab_test_report` labrep ON labrep.op_ip_appt_id = mhcmap.appt_id
WHERE
mhcmap.appt_id = 81

MYSQL - BASIC QUERYS where + group by + having

SELECT dieet.snr, soort.nsnaam FROM soort
JOIN dieet ON soort.snr = dieet.snr
JOIN voedsel ON dieet.voednr = voedsel.voednr
WHERE voedsel.voednr = 22
GROUP BY dieet.snr
HAVING COUNT(*) = 1 ;
the where condition messes up my output, what am i doing wrong
I suspect that you are looking for "snr"s that have exactly one record that is a "voednr = 22". Your query is getting all "snr"s that have exactly one such "voednr", along with other "voednr"s.
Let me suggest the following query:
SELECT dieet.snr, soort.nsnaam
FROM soort
JOIN dieet ON soort.snr = dieet.snr
JOIN voedsel ON dieet.voednr = voedsel.voednr
GROUP BY dieet.snr
HAVING COUNT(*) = 1 and max(voedsel.voednr) = 22
This will get you the rows with the one and only 22.