各个字段的子查询创建多个记录

时间:2016-02-03 17:59:54

标签: sql subquery teradata

我的方案:请求可能有多个(最多3个)拒绝代码。第一个是主要拒绝代码,次要(第二个和第三个)拒绝代码是可选的。要确定rejection_code排名,有一个名为rejection_rowId的字段。如果rejection_rowId =' 1',那么它就是主要拒绝。如果rejection_rowId =' 2',那么它就是第二次拒绝。如果它是' 3'它是第三个。现在,我尝试在一条记录中显示属于一个请求的所有rejection_code值,而不是为每个rejection_code存储1条记录。我遇到了麻烦,想知道是否有人可以解释为什么我的SQL无法正常工作。

我的SQL看起来基本上就是这样;

SELECT DISTINCT rea.id
    ,(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '1'
        AND t1.rowId = REA.rowId) AS rejection1

    ,(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '2'
        AND t1.rowId = REA.rowId) AS rejection2

    ,(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '3'
        AND t1.rowId = REA.rowId) AS rejection3

FROM reason rea
INNER JOIN rejection rej ON rea.rowId = rej.rowId
WHERE rea.id = '12345';

上述SQL生成的输出是......

id    | rejection1 | rejection2 | rejection3
12345 | 26         | NULL       | NULL
12345 | NULL       | 51         | NULL
12345 | NULL       | NULL       | 3

我尝试(和失败)生成的输出是......

id    | rejection1 | rejection2 | rejection3
12345 | 26         | 51         | 3

如果有人能帮我识别并解决问题,我将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:3)

我认为你正在尝试做这样的事情:

GROUP BY

不需要一次又一次地在相同的表之间加入,并且使用子查询来实现您的需求根本就没有必要,并且花费很多

使用{{1}}子句将结果限制为一行。对于聚合函数内的条件,只有在实际存在时才会在列中显示拒绝,并且您可以将它们拆分为单独的列。

答案 1 :(得分:1)

试试这个:

总结:

SELECT DISTINCT rea.id
    ,SUM(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '1'
        AND t1.rowId = REA.rowId) AS rejection1

    ,SUM(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '2'
        AND t1.rowId = REA.rowId) AS rejection2

    ,SUM(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '3'
        AND t1.rowId = REA.rowId) AS rejection3

FROM reason rea
INNER JOIN rejection rej ON rea.rowId = rej.rowId
WHERE rea.id = '12345'
GROUP BY rea.id ;

最多:

SELECT DISTINCT rea.id
    ,MAX(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '1'
        AND t1.rowId = REA.rowId) AS rejection1

    ,MAX(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '2'
        AND t1.rowId = REA.rowId) AS rejection2

    ,MAX(SELECT rejection_code 
      FROM rejection t1
      INNER JOIN reason t2 ON t1.rowId = t2.rowId
      WHERE t1.rejection_rowId = '3'
        AND t1.rowId = REA.rowId) AS rejection3

FROM reason rea
INNER JOIN rejection rej ON rea.rowId = rej.rowId
WHERE rea.id = '12345'
GROUP BY rea.id ;