如何使用别名加入表

时间:2015-01-29 17:54:04

标签: sql postgresql join alias

提前感谢您的帮助。

我想知道如何加入我所拥有的两个SQL语句,基于我已经给出列别名的事实。

源表看起来像这样(请记住,由于其他要求,更改此表的布局非常昂贵):

ColumnID    RowIdx    Val
1           0         "Mr A"
1           1         "Mr B"
1           2         "Mr C"
2           0         "M40 2TB"
2           1         "G23 XYN"
2           2         "HJ 23N"

我使用两个sql语句在表上创建视图,我认为这是加入的。这看起来像这样:

-- Statement #1
CREATE TEMP TABLE nameTable AS (SELECT 
    max(CASE WHEN ColumnID=1 THEN Val ELSE null END) AS Name, 
    row_number() over (ORDER BY RowIdx) AS rowindex 

FROM myTable 

WHERE (ColumnID=1) 

GROUP BY RowIdx
ORDER BY RowIdx);

-- Statement #2
CREATE TEMP TABLE postcodeTable AS (SELECT 
    max(CASE WHEN ColumnID=2 THEN Val ELSE null END) AS PostCode, 
    row_number() over (ORDER BY RowIdx) AS rowindex 

FROM myTable 

WHERE (ColumnID=2) 

GROUP BY RowIdx
ORDER BY RowIdx);

-- Statement #3
SELECT * FROM nameTable
INNER JOIN postcodeTable ON nameTable.rowIndex=postcodeTable.rowIndex

结果如下:

Name    PostCode    RowIndex
Mr A    M40 2TB     0
Mr B    G23 XYN     1
Mr C    HJ 23N      2

我想将这些组合成一个语句(因为它使我的程序生成语句更简单。

我已经选择从语句1和2中省略一些逻辑,因为它对于我的例子来说是不必要的复杂,但我遗漏的内容禁止我这样做:

SELECT 
    max(CASE WHEN ColumnID=1 THEN Val ELSE null END) AS Name, 
    max(CASE WHEN ColumnID=2 THEN Val ELSE null END) AS PostCode, 
    row_number() over (ORDER BY RowIdx) AS rowindex 

FROM myTable 

WHERE (ColumnID=1 OR ColumnID=2) 

GROUP BY RowIdx
ORDER BY RowIdx

我现在正在考虑做这样的事情,但我不确定它是否可能:

SELECT 
    max(CASE WHEN ColumnID=1 THEN Val ELSE null END) AS Name, 
    row_number() over (ORDER BY RowIdx) AS rowindex 

FROM myTable 

INNER JOIN (SELECT 
        max(CASE WHEN ColumnID=2 THEN Val ELSE null END) AS PostCode, 
        row_number() over (ORDER BY RowIdx) AS rowindex 

    FROM myTable 

    WHERE (ColumnID=2) 

    GROUP BY RowIdx
    ORDER BY RowIdx) AS postcodeTable ON rowIndex=postcodeTable.rowIndex

WHERE (ColumnID=1) 

GROUP BY RowIdx
ORDER BY RowIdx);

这是我应该考虑做的事吗?或者我应该坚持使用临时表?如果是,我如何让它工作? <{1}} rowIndex上的编译问题不存在。

我知道原始架构格式很奇怪,但有各种各样的外部原因。如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:2)

我可能会遗漏某些内容,但我不了解示例查询中复杂性的必要性。是否会像以下(未经测试的)查询一样工作?

SELECT Name, PostCode, A.RowIdx AS RowIdx 
FROM
    (SELECT Val AS Name, RowIdx FROM myTable WHERE ColumnID=1) A
    INNER JOIN
    (SELECT Val AS PostCode, RowIdx FROM myTable WHERE ColumnID=2) B
ON A.RowIdx = B.RowIdx;