如何简化SQL select命令

时间:2017-03-07 10:36:39

标签: sql sql-server

我的查询执行时间太长。请帮我简化一下? 这是我的疑问:

     SELECT uid,etop_id,SUM(amount) AS amt,
                    (SELECT m_name FROM member_details WHERE etop_id=a.etop_id) AS m_name,
                    (SELECT SUM(amount) FROM hidden_charges WHERE etop_id=a.etop_id 

    AND entry_date BETWEEN @date1 AND @date2 AND particular IS NULL
                    ) AS hidden,
                    (SELECT (SUM(credit)-SUM(debit)) 
                        FROM member_transaction
                        WHERE member_id=a.uid 
                        AND is_succeed=1 
                        AND isnull(reference_id,0) NOT IN( SELECT 
user_reference_id FROM recharge_request WHERE status=7)
                    ) AS balance,
                    (   SELECT TOP 1 credit 
                        FROM member_transaction 
                        WHERE member_id=a.uid 
                        AND credit>0 
                        AND entry_date=(SELECT MAX(entry_date) 
                                        FROM member_transaction 
                                        WHERE member_id=a.uid AND credit>0)) AS credit 
            FROM recharge_request a WHERE status=1 AND rdate BETWEEN @date1 AND @date2 
            GROUP BY etop_id, uid ORDER BY amt DESC

1 个答案:

答案 0 :(得分:0)

对于大型查询,我倾向于将数据弹出到临时表中并使用它来查询。

Select * 
Into #Table
From member_transaction 
Where member_id=a.uid 

然后只是查询#Table而不是member_transaction,应该加快速度。