SQL

时间:2015-06-10 06:13:44

标签: sql netezza

我想计算max(min(150,value returned by below query),50)。我如何在netezza中实现这一点?我需要将以下查询返回的值传递给上面的语句并计算表达式的值。感谢您的时间和帮助。

注意:按最小/最大值,我的意思是最大/最小SQL等价物。虽然在Neteeza中没有最大/最少的功能。

  SELECT ( x / cast(y  as float)* 100 AS sales_ratio
FROM   (SELECT a.sum(sales_amt) AS x
        FROM   table2 b, 
               table1 a,
               table 3 c
        WHERE  b.VEND_CD IN ($vendorCD1) AND
               b.ITM_CD_1 = ($ITMCD) AND
               b.area_num = ($area) AND
               b.area_num = a.area_num AND
               b.itm_cd_2 = a.itm_cd_2 AND
               a.week_end = c.week_end AND
               c.week_end BETWEEN ($startdate) AND ($enddate)) t1
CROSS JOIN (SELECT a.sum(sales_amt) AS y
            FROM   table2 b, 
                   table1 a,
                   table3 c
            WHERE  b.VEND_CD IN ($vendorCD1) AND
                   b.ITM_CD_1 = ($ITMCD) AND
                   b.area_num = ($area) AND
                   b.area_num = a.area_num AND
                   b.itm_cd_2 = a.itm_cd_2 AND
                   a.week_end = c.week_end AND
                   c.week_end BETWEEN ($startdate2) AND ($enddate2)) t2

3 个答案:

答案 0 :(得分:0)

这是一个粗略的估计,因为我不知道你正在使用的RDBMS。一般的想法是实现一个CASE语句,就像你已经举例说明的MAX(MIN())组合一样。

SELECT 
    x / cast(y AS FLOAT) * 100 AS sales_ratio
    ,CASE 
         WHEN CASE 
                 WHEN x / cast(y AS FLOAT) * 100 > 150
                    THEN 150
                 ELSE x / cast(y AS FLOAT) * 100
              END < 50
         THEN x / cast(y AS FLOAT) * 100
     ELSE 50
    END Result     
FROM (
    SELECT a.sum(sales_amt) AS x
    FROM table2 b
        ,table1 a
        ,TABLE 3 c
    WHERE b.VEND_CD IN ($VENDORCD1)
        AND b.ITM_CD_1 = ($ITMCD)
        AND b.area_num = ($AREA)
        AND b.area_num = a.area_num
        AND b.itm_cd_2 = a.itm_cd_2
        AND a.week_end = c.week_end
        AND c.week_end BETWEEN ($STARTDATE)
            AND ($ENDDATE)) t1
CROSS JOIN (
    SELECT a.sum(sales_amt) AS y
    FROM table2 b
        ,table1 a
        ,table3 c
    WHERE b.VEND_CD IN ($VENDORCD1)
        AND b.ITM_CD_1 = ($ITMCD)
        AND b.area_num = ($AREA)
        AND b.area_num = a.area_num
        AND b.itm_cd_2 = a.itm_cd_2
        AND a.week_end = c.week_end
        AND c.week_end BETWEEN ($STARTDATE2)
            AND ($ENDDATE2)) t2

答案 1 :(得分:0)

一般方法使用CASE表达式虽然在Netezza中可能没有很好地优化(根据我浏览的另一个SO答案。)您可能希望在变量中捕获查询结果然后应用使值不超出50到150范围的逻辑,但我认为Netezza不允许变量。也许最好在SQL之外做这个部分,特别是因为nulls的可能性是另一个复杂因素。

答案 2 :(得分:0)

在Netezza版本7.2中,引入了类似于GREATEST和LEAST的标量MAX和MIN函数。