简体   繁体   中英

SQL Server Query Performance Issue

I have about 1,60,000 rows retrieved in 4 mins if I use following.

SELECT DISTINCT * 
FROM 
     (ABOUT 10 TABLES WITH LEFT OUTER JOIN )

But I need to extract only about 25 columns with some basic operations on them. But my below query is taking forever to execute (beyond an hour).

Col1, Col2 etc, ColA, ColB etc represents columns. Also I need to have DISTINCT on them because that is the final version that I need.

SELECT DISTINCT 
    Col1, Col2,...Col23,
    Table1.Description1 + Table1.Description2 as FinalDescription,
    (CASE WHEN COLA = 'XX' THEN 
            cast(round(COLB,2) as numeric(10,2))
          ELSE 
            cast(round(COLB*-1  ,2) as numeric(10,2))
     END) AS 'Amount',
    CASE WHEN ISNULL(COLC,'')='' 
            THEN  COLD + 'TO' +  COLE
         WHEN SUBSTRING ( COLC ,1 , 3 )IN ('XY')  
            THEN  COLD+','+ SUBSTRING (COLE ,5 , 12)
         ELSE  COLD + ','+ COLF
    END as 'Custom_Column'
FROM 
    (ABOUT 10 TABLES WITH LEFT OUTER JOIN) 

What should I do to improve the performance to get the columns in the format that I am interested in?

If you run your second query without distinct is faster? Maybe you can calculate your custom column and then perfom an union.

   SELECT *, 'Amount', 'Custom_Column'
   FROM Your Query
   UNION 
   SELECT 0.*, 0 as 'Amount', 0 as 'Custom_Column'

Anyway if you provide an explain plan and tell us what is your db we can give you better suggestions.

Below CASE statement in select is causing the issue. I just removed it from SELECT but DID NOT alter any join conditions & it finished very quickly. I am not sure why this below simple case statement is causing a performance issue. Any inputs on how to improve this?

   (CASE WHEN tabled.col5 = 'ABCD' THEN 'ABCD'

   ELSE 'UVWX' END) AS [Mode],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM