分组和自我加入

时间:2014-01-26 13:43:21

标签: sql oracle

我有一个包含以下结构的表

Txn_id Varchar
Role   Varchar
Acid   Varchar
RefTxt Varchar

现在,当Role列的类型为“Transporter”时,RefTxt列将只包含数据。角色还可以占用“发件人”和“接收者”

这些值

我想以这样的方式查询表格,以获得以下输出

Txn_id   Sender_Acid   Reciever_Acid
Tx001    SAC001        RAC001       

为此,我编写了查询

SELECT
    myTable.Txn_id,
    MAX(CASE WHEN role = 'Sender' THEN myTable.acid END)    AS sender_acid,
    MAX(CASE WHEN role = 'Recipient' THEN myTable.acid END) AS recipient_acid

FROM 
    myTable,
    (
      SELECT txn_id, reftext
      FROM   myTable
      WHERE  role = 'Transporter'
    ) SubQuery
WHERE     SubQuery.txn_id = myTable.txn_id
AND       myTable.role in ('Sender', 'Receiver')
GROUP BY  mytable.txn_id;

我希望结果每个txn_id包含一行,其中包含相应帐户的字段Sender_Acid和Receiver_Acid。但是对于某些Txn_id,我得到两个单独的行,其中Sender_acid或receiver_acid为NULL。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我不确定您的查询有什么问题,但您可以将其简化为:

SELECT myTable.Txn_id,
       MAX(CASE WHEN role = 'Sender' THEN myTable.acid END)    AS sender_acid,
       MAX(CASE WHEN role = 'Recipient' THEN myTable.acid END) AS recipient_acid
FROM myTable join
     myTable Subquery
     on SubQuery.txn_id = myTable.txn_id and
        Subquery.role = 'Transporter'
WHERE myTable.role in ('Sender', 'Receiver')
GROUP BY  mytable.txn_id;

如果你得到两行看起来像Txn_id那样,那是因为那些id真的不同。也许一个人以空间结束。要查看此内容,请尝试以下select

select '|'||myTable.Txn_id||'|',

这将在id周围放置垂直条,以便您可以看到任何额外的字符。