Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query Optimization

Author  Topic 

mcupples
Starting Member

9 Posts

Posted - 2007-03-12 : 11:17:36
Okay guys, this will probably be messy. Just throw out some thoughts and I'll deal with it. How do I make this query smaller and more efficient?

Query deleted and link posted: http://theninjalist.com/

snSQL
Master Smack Fu Yak Hacker

1837 Posts

Posted - 2007-03-12 : 11:23:51
You can start by formatting it with line breaks and indentation and posting it in a code block on the forum, so that we can read it more easily
Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-03-12 : 11:52:40
One thing that comes to my mind is you are using lots of CASEs which can significantly affect the performance. Try to convert those cases into WHERE conditions.

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

mcupples
Starting Member

9 Posts

Posted - 2007-03-12 : 12:01:06
Okay, I'm not sure if I should in here. I will format it and shove it on my site for now and link you guys to it. It's just massive, that's why I was hesitant. If you want it here I'll do it, though.

http://theninjalist.com/

As for the cases, I'll check that out - thanks.
Go to Top of Page

snSQL
Master Smack Fu Yak Hacker

1837 Posts

Posted - 2007-03-12 : 12:33:40
You should create a view that gives you the date you want then when you create all those amount columns you can just use the date without that extra CASE for every column. Here is how the view could be, I named the date ActiveDate. I also joined the payee table instead of using an IN in the WHERE clause

CREATE VIEW MyView
AS
SELECT a.company_id,
a.payee_id,
a.amount,
a.ready_to_pay_flag,
a.deduction_type,
CASE
WHEN b.order_id IS NULL
THEN a.transaction_date
ELSE b.delivery_date
END AS ActiveDate
FROM drs_pending_deduct as a
INNER JOIN payee p ON a.payee_id = p.[id]
LEFT OUTER JOIN settlement as b
ON a.order_id = b.order_id
WHERE a.company_id = 'TMS2'
AND p.status = 'A'
AND p.non_office_emp = 'Y'
AND p.company_id = 'TMS2'
AND a.ready_to_pay_flag <> 'V'
AND a.amount is not null


Your query now becomes something like


SELECT company_id, payee_id,
sum(
CASE
WHEN ready_to_pay_flag = 'Y'
AND deduction_type = 'E'
THEN amount
END) earn_amount_rtp,
sum(
CASE
WHEN ready_to_pay_flag = 'Y'
AND deduction_type = 'E'
AND datediff(d,(
ActiveDate, '2007-03-12 23:59:59') <= 30
THEN amount
END) earn_amount_rtp_current,
...
FROM MyView
GROUP BY company_id, payee_id
Go to Top of Page
   

- Advertisement -