MYSQL Syntax Assistance - mysql

Can anyone point me in the right direction with this query please?
Whichever way i try i continue to get errors
SELECT b.SOLD_TO
, b.CUSTOMER
, b.JANUARY_BUDGET
, Round(sum(d.TOTAL_WEIGHT)/1000,2) AS MONTHLY_DESPATCH
, if(sum(d.TOTAL_WEIGHT)/1000=0 AND b.JANUARY_BUDGET=0,"DOUBLE_ZERO",
if(sum(d.TOTAL_WEIGHT)/1000>0 AND b.JANUARY_BUDGET=0,"NO_BUDGET_GOOD_SHIPMENT",
if(sum(d.TOTAL_WEIGHT)/1000>0 AND b.JANUARY_BUDGET>0 AND (sum(d.TOTAL_WEIGHT)/1000> b.JANUARY_BUDGET,"ABOVE_BUDGET",
if(sum(d.TOTAL_WEIGHT)/1000>0 AND b.JANUARY_BUDGET>0 AND (sum(d.TOTAL_WEIGHT)/1000< b.JANUARY_BUDGET,"POOR_RESULT")))) AS PERFORMANCE
FROM budget2021 b
left JOIN despatches2021 d on d.SOLD_TO = b.SOLD_TO
WHERE b.SOLD_TO=69946 AND d.INVOICE_DATE BETWEEN 20210101 and 20210131
GROUP BY b.SOLD_TO
, b.CUSTOMER
, b.JANUARY_BUDGET

Hm, to diffult to explain, what you made wron a
An IF( condition,true,false) is the form independent of how many you nested.
A godd code indentation helps to handle such things
I also had to add a NULL at the end of the last IF as i don't knpw really where you want to go with this
SELECT
b.SOLD_TO,
b.CUSTOMER,
b.JANUARY_BUDGET,
ROUND(SUM(d.TOTAL_WEIGHT) / 1000, 2) AS MONTHLY_DESPATCH,
IF(SUM(d.TOTAL_WEIGHT) / 1000 = 0
AND b.JANUARY_BUDGET = 0,
'DOUBLE_ZERO',
IF(SUM(d.TOTAL_WEIGHT) / 1000 > 0
AND b.JANUARY_BUDGET = 0,
'NO_BUDGET_GOOD_SHIPMENT',
IF(SUM(d.TOTAL_WEIGHT) / 1000 > 0
AND b.JANUARY_BUDGET > 0
AND (SUM(d.TOTAL_WEIGHT) / 1000 > b.JANUARY_BUDGET),
'ABOVE_BUDGET',
IF(SUM(d.TOTAL_WEIGHT) / 1000 > 0
AND b.JANUARY_BUDGET > 0
AND (SUM(d.TOTAL_WEIGHT) / 1000 < b.JANUARY_BUDGET),
'POOR_RESULT',
NULL)))) AS PERFORMANCE -- here i added the NULL
FROM
budget2021 b
LEFT JOIN
despatches2021 d ON d.SOLD_TO = b.SOLD_TO
WHERE
b.SOLD_TO = 69946
AND d.INVOICE_DATE BETWEEN 20210101 AND 20210131
GROUP BY b.SOLD_TO , b.CUSTOMER , b.JANUARY_BUDGET

Related

Error Query SQL "Invalid use of group function"

I'm trying run this query but i got this error "Invalid use of group function". Also tried group by Año, Mes, Turno; and same result.
Also I want to multiply the THEN by 100 so that the result is a percentage, I must do it on the same line of THEN or at the end before AS?
select year(c.start) as Año, month(c.start) as Mes, s.name as Turno,
SUM(
CASE
WHEN u.name ='Jorge Robles Ruiz'
THEN SUM(TIMESTAMPDIFF(SECOND,c.start,c.end)/3600) /
SUM(TIMESTAMPDIFF(SECOND,s.startTime,s.endTime)/3600)
ELSE 0
END
) AS 'Jorge Robles Ruiz',
SUM(
CASE
WHEN u.name ='Ricardo Jarquín'
THEN SUM(TIMESTAMPDIFF(SECOND,c.start,c.end)/3600) /
SUM(TIMESTAMPDIFF(SECOND,s.startTime,s.endTime)/3600)
ELSE 0
END
) AS 'Ricardo Jarquín'
from `cicles` as `c`
inner join `users` as `u` on `u`.`id` = `c`.`opId` and `u`.`companies_id` = `c`.`companies_id`
inner join `shifts` as `s` on `s`.`id` = `c`.`shiftId` and `s`.`companies_id` = `c`.`companies_id`
where `c`.`start`
between 2018-12-01 and 2019-01-11
and `c`.`opId` in (1, 2)
and `s`.`visible` = 1
and `c`.`companies_id` = 1
and `c`.`status` = 1
group by year(c.start), month(c.start), s.name;
Thank you guys!
PD. Sorry for my bad English.
You can't have SUM() inside SUM(), and I don't think you need them both here. I think you should write:
SUM(IF(u.name = 'Jorge Robles Ruiz', TIMESTAMPDIFF(SECOND,c.start,c.end), 0))
/ SUM(IF(u.name = 'Jorge Robles Ruiz', TIMESTAMPDIFF(SECOND,s.startTime,s.endTime), 0))
/ 3600 AS 'Jorge Robles Ruiz',
To make it a percentage, multiply by 100 at the end, or just change / 3600 to / 36.

Combining conditions for CASE, mysql query

I'm trying to finish up a query to total different numbers for our people on the phones and I have the standard totals calculated fine, it seems, but I'm now trying to do this:
For every total column (total calls, total inbound, total outbound, total missed) I now need to have a new column partnered with it for known numbers in our database (so I'll have total calls known, total inbound known, etc.).
The way I'm doing this is by checking two fields in my session table: callingpartyno and finallycalledpartyno. So, for every call in session I need to check to see if the number in either of those fields are in my knownNumbers table in the phone_number field. If so, I need to count them for the known column.
About 8 lines down in my query below, I have my first instance of this which seems to be showing accurate numbers, but it's only incorporating callingpartyno. I first need to know how to combine conditions in this 'case whento addfinallycalledpartyno` as well.
The other issue is that for inbound and outbound, I need to base the phone number field I'm using on the LEGTYPE field. So, for example, IF I'm calculating outbound calls to known numbers I need something like
sum(if(LEGTYPE1 = 1,1,0)) AND finallycalledpartno = k.phone_number AS Total_Outbound_known.
I hope this makes sense, and it should be pretty straightforward for an advanced SQL programmer. I just can't seem to get the combination of conditions in a case when statement to work especially.
Query below:
SELECT u.firstn
,u.lastn
,c.extension
,SUM(IF(LEGTYPE1 = 1, 1, 0)) + -- outbound calls
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) + -- inbound calls
SUM(IF(Answered = 1, 0, 1)) AS Total_Calls
,sum(case when CALLINGPARTYNO = k.phone_number then 1 else 0 end ) AS total_known
,sum(if(Answered = 1,0,1)) AS Total_Missed
,sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Recieved
,sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
,round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
,sum(if(Answered = 1,0,1)) / (SUM(IF(LEGTYPE1 = 1, 1, 0)) + -- outbound calls
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) + -- inbound calls
SUM(IF(Answered = 1, 0, 1))) * 100 AS Percentage_Missed
FROM ambition.session a
INNER JOIN ambition.callsummary b
ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c
ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u
on c.extension = u.extension
left join ambition.knownnumbers k
on a.callingpartyno = k.phone_number
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
group by c.extension;
Apart what I wrote in above comments, I would rewrite your query like this (I think at least it should be easier to read it, avoiding to repeat some SUMs)
SELECT firstn
, lastn
, extension
, Total_Outbound+Total_Missed+Total_Received AS Total_Calls
, Total_Known
, Total_Missed
, Total_Received
, Total_Outbound
, Total_Talk_Time_minutes
, Total_Missed / (Total_Outbound+Total_Missed+Total_Received) * 100 AS Percentage_Missed
FROM (
SELECT u.firstn
, u.lastn
, c.extension
, sum(case when CALLINGPARTYNO = k.phone_number then 1 else 0 end ) AS Total_Known
, sum(if(Answered = 1,0,1)) AS Total_Missed
, sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received
, sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
FROM ambition.session a
INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
LEFT JOIN ambition.knownnumbers k ON a.callingpartyno = k.phone_number
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
GROUP BY c.extension, u.firstn, u.lastn
) X;

Expressing formula within a SELECT query

I have this existing query:
SELECT
extension
, Total_Outbound+Total_Missed+Total_Received AS Total_Calls
, Total_Missed
, Total_Talk_Time_minutes
FROM (
SELECT
, extension
, sum(if(Answered = 1,0,1)) AS Total_Missed
, sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received
, sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
FROM session a
GROUP BY extension
) x;
It works great but I need to add a metric/formula to it called missed_call_score right under Total_Talk_Time_Minutes.
The formula for the missed call score is this:
(missed calls/total talk time) * (average calls per CSR/total calls) * 100 but one thing to note is that the average calls per csr needs to ignore the MAX and MIN, so the lowest and highest number of calls taken.
I'm not sure how I could construct this score within a single select variable or the syntax I would use for this given the fact that it has to throw out the max and min.
Here is an example of my needed output and the formulas it should be using:
extension | Total calls | missed calls | total talk time | missed call score
----------------------------------------------------------------------------
1234 8 4 15.5 5.7
4321 4 0 9.42 0.0
5678 5 2 6.78 6.5
9876 13 6 18.3 7.2
Total call sum = 30
Total call sum without high and low = 13
average calls per CSR = (13/2) = 6.5
extension 1 = (4/15.5) * (6.5/30) * 100 = 5.7
extension 2 = (0/9.42) * (6.5/30) * 100 = 0.0
extension 3 = (2/6.78) * (6.5/30) * 100 = 6.5
extension 4 = (6/18.3) * (6.5/30) * 100 = 7.2
The data above for extension, total calls, missed calls and talk time are taken from my sql fiddle, linked below. I simply added the score column to give example of my expected output.
The fiddle linked below shows my create and inserts so hopefully that gives everything needed to assist me with this.
**sql fiddle
**
http://sqlfiddle.com/#!9/aa1f9/1
UPDATE
Full production query with joins
SELECT firstn ,
lastn ,
extension ,
Total_Outbound+Total_Missed+Total_Received AS Total_Calls ,
Total_Missed ,
Total_Talk_Time_minutes ,
Total_All_Calls ,
Max_Calls ,
Min_Calls ,
CSR_Count ,
((Total_Missed/Total_Talk_Time_minutes) *
(((Total_All_Calls-Max_Calls-Min_Calls)/CSR_Count)/Total_All_Calls)) * 100
FROM ( SELECT u.firstn ,
u.lastn ,
c.extension ,
sum(if(Answered = 1,0,1)) AS Total_Missed ,
sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received ,
sum(CASE WHEN LEGTYPE1 = 1 THEN 1 ELSE 0 END) AS Total_Outbound ,
round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes ,
(SELECT COUNT(1) FROM ambition.session a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)) Total_All_Calls ,
(SELECT MAX(CNT) FROM (SELECT COUNT(1) CNT, c.extension
FROM ambition.SESSION a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312) GROUP BY responsibleuserextensionid) y) Max_Calls ,
(SELECT MIN(CNT) FROM (SELECT COUNT(1) CNT, c.extension
FROM ambition.SESSION a
INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)GROUP BY responsibleuserextensionid) y) Min_Calls ,
(SELECT COUNT(DISTINCT c.extension)-2
FROM ambition.SESSION a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)) CSR_Count
FROM ambition.session a
INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
LEFT JOIN ambition.knownnumbers k ON a.callingpartyno = k.phone_number
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
GROUP BY c.extension, u.firstn, u.lastn ) x
This should work for you:
SELECT
extension
, Total_Outbound+Total_Missed+Total_Received AS Total_Calls
, Total_Missed
, Total_Talk_Time_minutes
, Total_All_Calls
, Max_Calls
, Min_Calls
, CSR_Count
, ((Total_Missed/Total_Talk_Time_minutes) *
(((Total_All_Calls-Max_Calls-Min_Calls)/CSR_Count)/Total_All_Calls)) * 100
FROM (
SELECT
extension
, sum(if(Answered = 1,0,1)) AS Total_Missed
, sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received
, sum(CASE WHEN ANSWERED = 1 AND LEGTYPE1 = 1 THEN 1 ELSE 0 END) AS Total_Outbound
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
, (SELECT COUNT(1) FROM session) Total_All_Calls
, (SELECT MAX(CNT) FROM (SELECT COUNT(1) CNT, EXTENSION FROM SESSION GROUP BY EXTENSION) y) Max_Calls
, (SELECT MIN(CNT) FROM (SELECT COUNT(1) CNT, EXTENSION FROM SESSION GROUP BY EXTENSION) y) Min_Calls
, (SELECT COUNT(DISTINCT EXTENSION)-2 FROM SESSION) CSR_Count
FROM session a
GROUP BY extension
) x;
Here is the fiddle.
Basically I used sub-counts in your derived table x to get each of the variables needed for missed_call_score. One major thing worth noting is that the logic was off for Total_Outbound, so I tweaked that to a CASE statement instead of an IF(). I selected the count columns in the outer query just so you can see what is going on, you can remove those.
I've done something similar in the past and extracted this snippet from my code.
I think/hope that this might help you getting started (I left out most of the columns from your query and you'd have to adjust avg(amount) to match your formula.
select extension, avg(amount) from
(
select t.*,
min(amount) over (partition by extension) as min_amt,
max(amount) over (partition by extension) as max_amt
from your_table t
) t
where amount > min_amt and amount < max_amt group by extension;

Change Null with 0

I have tried to run a query I phpmyAdmin as follows
SELECT
orders_history.id,
orders_history.`items`,
orders_history.`transaction_id`,
orders_history.`quantity`,
estockClaims.`esquantity`,
IFNULL( esquantity, 0 ),
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims
ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
And it gives me this result:
----------------------------------------------------------------------
id items transaction_id quantity esquantity IFNULL(esquantity , 0 ) myquantity
1 FR 001 100 NULL 0 NULL
2 BR 002 10 NULL 0 NULL
3 WR 003 25 25 25 0
4 CR 004 50 3 3 47
How to solve this so that NULL is not NULL anyomre but change to 0. Thanks in advance.
Thanks
You already have it in the next column. What you need to do is to drop the original esquantity column and make an alias for the IFNULL... column, like this:
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` ,
orders_history.`quantity` , IFNULL( esquantity, 0 ) AS esquantity,
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
The change I mentioned is in the line 2 above.
UPDATE
To get
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
to show expected results, you need to "unnullify" the esquantity field again so that the subtraction would work:
orders_history.`quantity` - IFNULL( estockClaims.`esquantity`, 0 ) AS myquantity
That would ensure you no longer get, for example:
100 - NULL
but this instead:
100 - 0
which will return a proper value.
You can also skip the whole subtraction thing if esquantity is NULL and simply use the value of quantity.
you can use IF to check the esquantity and myquantity columns:
IF(esquantity IS NULL, 0, esquantity)
and
IF(myquantityIS NULL, 0, myquantity)
or use IFNULL as DanFromGermany said
Reason is you are using it as select instead of when doing subtraction. Use it as below:
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` , orders_history.`quantity` , orders_history.`quantity` - IFNULL( esquantity, 0 ) AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100
select temp.id, items, transaction_id, quantity, ifNULL(esquantity, 0), ifNULL(myquantity, 0)
from (SELECT
orders_history.id,
orders_history.`items`,
orders_history.`transaction_id`,
orders_history.`quantity`,
estockClaims.`esquantity`
orders_history.`quantity` - estockClaims.`esquantity` AS myquantity
FROM orders_history
LEFT JOIN estockClaims
ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100) temp
You can also use COALESCE to replace the NULL value to 0
check this query.
SELECT orders_history.id, orders_history.`items` , orders_history.`transaction_id` ,
orders_history.`quantity` , COALESCE( esquantity, 0 ) AS esquantity,
orders_history.`quantity` - COALESCE(estockClaims.`esquantity`, 0) AS myquantity
FROM orders_history
LEFT JOIN estockClaims ON orders_history.transaction_id = estockClaims.transaction_id
AND orders_history.items = estockClaims.items
LIMIT 0 , 100

Sum() slows down my query

I am using sum() inside case statement. But this slows down my query. Is there any other way for this. This is the query. Please help me.
SELECT (SUM(PRI_INS_AGING) + SUM(SEC_INS_AGING) + SUM(TER_INS_AGING)) AS INS_AGING,SUM(PAT_AGING) AS PAT_AGING FROM
(SELECT
CASE WHEN L.RESP_PARTY =1 AND VP.STATUS IN(3,5) AND VP.PRIMARY_PAID =0 AND VP.PRIMARY_PENDING >0 AND C.PRIMARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS PRI_INS_AGING,
CASE WHEN L.RESP_PARTY =2 AND VP.STATUS IN(6,7,5) AND VP.SECONDARY_PAID =0 AND VP.SECONDARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND C.SECONDARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS SEC_INS_AGING,
CASE WHEN L.RESP_PARTY =3 AND VP.STATUS IN(8,9,5) AND VP.TERTIARY_PAID =0 AND VP.TERTIARY_PENDING >0 AND VP.PRIMARY_PENDING <=0 AND VP.SECONDARY_PENDING <=0 AND C.TERTIARY_PAYER_ID >0 AND C.HIDEN=0 THEN SUM(L.AMOUNT) ELSE 0 END AS TER_INS_AGING,
CASE WHEN L.RESP_PARTY =4 THEN SUM(L.AMOUNT) ELSE 0 END AS PAT_AGING
FROM VISIT_PROCEDURE VP
JOIN CLAIM C
ON (C.CLAIM_ID = VP.CLAIM_ID AND C.CLINIC_ID = VP.CLINIC_ID)
JOIN LEDGER L
ON (L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID)
WHERE C.CLINIC_ID = 34847 AND L.TYPE IN(1,8,9,10,11) AND L.ACTIVE=1
GROUP BY VP.PROCEDURE_ID,L.TYPE,L.RESP_PARTY,L.ACTIVE)T1
Thanks
Sunil
without extra dissecting your SQL, look into your join on LEDGER... you have it doing the CLAIM_ID on the same value...
JOIN LEDGER L ON L.CLAIM_ID = L.CLAIM_ID AND VP.CLINIC_ID = L.CLINIC_ID
Should the "L.Claim_ID" be joined to a "VP.Claim_ID"??? or something else?
Ok, so with a little bit of time, I came up with this... I would swap the query around some. In addition, make sure you have an index ON your CLAIM table on Clinic_ID AND Hiden. Also, your inner query is breaking down the SUM of distinct parts of insurance claims, yet you are not doing anything ELSE with them except summing them in the outer. I would change to just sum ONCE at the outer for the given conditions
SELECT STRAIGHT_JOIN
SUM( IF( L.RESP_PARTY = 1
AND VP.STATUS IN(3,5)
AND VP.PRIMARY_PAID = 0
AND VP.PRIMARY_PENDING > 0
AND C.PRIMARY_PAYER_ID > 0, L.AMOUNT, 0 )
+
IF( L.RESP_PARTY = 2
AND VP.STATUS IN(6,7,5)
AND VP.SECONDARY_PAID = 0
AND VP.SECONDARY_PENDING > 0
AND VP.PRIMARY_PENDING <= 0
AND C.SECONDARY_PAYER_ID > 0, L.AMOUNT, 0 )
+
IF( L.RESP_PARTY = 3
AND VP.STATUS IN(8,9,5)
AND VP.TERTIARY_PAID = 0
AND VP.TERTIARY_PENDING > 0
AND VP.PRIMARY_PENDING <= 0
AND VP.SECONDARY_PENDING <= 0
AND C.TERTIARY_PAYER_ID > 0, L.AMOUNT, 0 ) ) as INS_AGING,
SUM( IF( L.RESP_PARTY = 4, L.AMOUNT, 0 )) as PAT_AGING
FROM
CLAIM C
JOIN VISIT_PROCEDURE VP
ON C.CLAIM_ID = VP.CLAIM_ID
AND C.CLINIC_ID = VP.CLINIC_ID
JOIN LEDGER L
ON VP.CLINIC_ID = L.CLINIC_ID
AND VP.CLAIM_ID = L.CLAIM_ID
AND L.TYPE IN ( 1, 8, 9, 10, 11 )
AND L.ACTIVE = 1
WHERE
C.CLINIC_ID = 34847
AND C.HIDEN = 0
If you're looking to get the SUM() of your data, I don't see you getting it any other way. That said, this is pretty complex and you might benefit from breaking it down into a stored proc and splitting the calculations up into stages.
Btw what does slow mean here? 1 second rather than 0.001? Or, 2 minutes?