我已经编写了以下查询,但我现在想要优化代码,最终要求是不要重复任何参数两次。有没有办法重写这个SQL查询而不重复Flag1和Flag2参数而不影响逻辑?
SELECT
CASE WHEN @PARAM1 = 'REV' THEN SUM(NET_INVOICE_REVENUE) ELSE SUM(QUANTITY) END VAL
FROM
PA_TRANS TR
JOIN
PA_SOLD_TO CUST
ON
TR.SOLD_TO_CUSTOMER = CUST.SOLD_TO_CUSTOMER
WHERE
AGREEMENT_NBR = @AGREEMENT_CSV
AND
PART_NUMBER = @PART_NUMBER
AND
CUST.WW_CORP = CASE WHEN (@FLAG1 = 'N' AND @FLAG2 ='N') THEN @WW_CORP ELSE CUST.WW_CORP END
AND
CUST.WW_AFFLIATE = CASE WHEN (@FLAG1 = 'N' AND @FLAG2 ='Y') THEN @WW_AFFLIATE ELSE CUST.WW_AFFLIATE END
AND
( DAY >= @A_START_DATE AND DAY < @A_END_DATE)
感谢。 Mayurika
答案 0 :(得分:0)
如果您只想提一次参数,可以使用CTE或子查询。这是子查询形式:
SELECT (CASE WHEN p_PARAM1 = 'REV' THEN SUM(NET_INVOICE_REVENUE) ELSE SUM(QUANTITY)
END) as VAL
FROM (select @PARAM1 as p_param1, @AGREEMENT_CSV as p_AGREEMENT_CSV,
@PART_NUMBER as p_PART_NUMBER, @FLAG1 as p_FLAG1, @FLAG2 as p_FLAG2,
@A_START_DATE as p_A_START_DATE, @A_END_DATE as p_A_END_DATE
) params CROSS JOIN
PA_TRANS TR JOIN
PA_SOLD_TO CUST
ON TR.SOLD_TO_CUSTOMER = CUST.SOLD_TO_CUSTOMER
WHERE AGREEMENT_NBR = p_AGREEMENT_CSV AND
PART_NUMBER = p_PART_NUMBER AND
CUST.WW_CORP = CASE WHEN (p_FLAG1 = 'N' AND p_FLAG2 ='N') THEN @WW_CORP ELSE CUST.WW_CORP END AND
CUST.WW_AFFLIATE = CASE WHEN (p_FLAG1 = 'N' AND p_FLAG2 ='Y') THEN @WW_AFFLIATE ELSE CUST.WW_AFFLIATE END AND
( DAY >= p_A_START_DATE AND DAY < p_A_END_DATE);