DB2是否有元组类型?

时间:2015-01-27 11:50:25

标签: sql db2 row tuples

我在DB2中实现了一个长的派生逻辑,其中定义了几个变量:

SELECT <other variables>
     , CASE
          <long logic, return variable_1>
       END AS variable_1
     , <...>
     , CASE
          <same long logic, return variable_n>
       END AS variable_n

FROM <...>

不是一次又一次地重复逻辑,是否可以使用某种形式的元组类型(例如,XML或TABLE数据类型),这将允许以下这样的事情?

SELECT <other variables>
     , CASE
          <long logic, return tuple of variables 1 to n>
       END AS variable_tuple       //example, doesn't work

FROM <...>

如果是这样,如何在后续步骤中访问元组元素?

1 个答案:

答案 0 :(得分:2)

据我所知,没有元组类型。我倾向于解决这个问题的方法是将long表达式移动到subuery,然后创建一个表以加入expresison的不同结果,这允许多列,例如:

SELECT  expr.T1, expr.T2, expr.T3, COUNT(*) AS Count
FROM    (   SELECT  CASE WHEN ID < 100 THEN 1
                        WHEN ID < 200 THEN 2
                        WHEN ID < 300 THEN 3
                        WHEN ID < 400 THEN 4
                        WHEN ID < 500 THEN 5
                        WHEN ID < 600 THEN 6
                        WHEN ID < 700 THEN 7
                        WHEN ID < 800 THEN 8
                        WHEN ID < 900 THEN 9
                        ELSE 10
                    END AS Result
            FROM    T
        ) AS sq
        INNER JOIN
        (   SELECT  1 AS Result, 2 AS T1, 3 AS T2, 'test1' AS T3 UNION ALL
            SELECT  2 AS Result, 3 AS T1, 4 AS T2, 'test2' AS T3 UNION ALL
            SELECT  3 AS Result, 4 AS T1, 5 AS T2, 'test3' AS T3 UNION ALL
            SELECT  4 AS Result, 5 AS T1, 6 AS T2, 'test4' AS T3 UNION ALL
            SELECT  5 AS Result, 6 AS T1, 7 AS T2, 'test5' AS T3 UNION ALL
            SELECT  6 AS Result, 7 AS T1, 8 AS T2, 'test6' AS T3 UNION ALL
            SELECT  7 AS Result, 8 AS T1, 9 AS T2, 'test7' AS T3 
        ) AS expr
            ON expr.Result = sq.Result
GROUP BY expr.T1, expr.T2, expr.T3;

它非常冗长,但这意味着表达式只被评估一次,并且从派生表中添加/删除行相当容易。