How to make this SQL line more efficient? (Case when in Partition By)

前端 未结 2 549
春和景丽
春和景丽 2021-01-26 03:45

I have a SQL line that looks like this

,SUM(Unit_Retail) OVER (PARTITION BY CASE WHEN @LocalDetailLevel = \'master\' THEN Master_Item WHEN @LocalDetailLevel = \'         


        
相关标签:
2条回答
  • 2021-01-26 04:14

    From an efficiency perspective,

    CASE
        WHEN @LocalDetailLevel = 'master' THEN SUM(Unit_Retail) OVER (PARTITION BY Master_Item)
        WHEN @LocalDetailLevel = 'size' THEN SUM(Unit_Retail) OVER (PARTITION BY Item_Number)
        WHEN @LocalDetailLevel = 'color' THEN CONCAT(Item_Number, Color_Code)
    END AS Sum_Unit_Retail
    

    Will you your best bet here. Without knowing the intricacies of your data, this seems to logically take the least amount of operations to complete, which is a good sign from an efficiency perspective.

    If you'd like, you could compare it against your current performance by following the steps here.

    0 讨论(0)
  • 2021-01-26 04:17

    For us to help, we need a few things from you. Start with this blog on Getting Help With a Slow Query. A big thing we need is the execution plan via PasteThePlan.com

    One issue you could be running into is Parameter Sniffing. This is where the execution plan really helps see where your query is hitting performance walls.

    Regarding the last part of your question, where you created a new question...

    CASE is an expression and thus isn't used to control logical flow.

    CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING

    For your problem, you would use IF...ELSE.

    The syntax is very similar...

    IF @LocalDetailLevel = 'master' 
    BEGIN
    ...
    END
    
    IF @LocalDetailLevel = 'size'
    BEGIN
    ...
    END
    
    0 讨论(0)
提交回复
热议问题