通过选择查询将列拆分为两个

时间:2015-06-08 11:28:20

标签: sql postgresql

我有一张像......的桌子。

 +-----+-------------+--------+
 |  ID | EarningName |  Type  |
 +-----+-------------+--------+
 | 101 | ravi        |  R     |
 | 103 | sadham      |  D     |
 | 103 | sadham      |  D     |
 | 102 | rahul       |  D     |
 | 101 | rakhav      |  R     |
 | 101 | nithin      |  R     |
 | 103 | sumesh      |  D     | 
 | 101 | joil        |  R     |
 | 101 | manu        |  R     |
 | 102 | mubi        |  R     |
 | 103 | pradeep     |  D     |
 | 102 | sree        |  R     |
 | 102 | sajeev      |  R     |
 | 102 | ansu        |  R     |
 | 101 | prasad      |  D     |
 | 103 | milin       |  R     |
 | 103 | abhilash    |  R     |
 | 102 |    praveen  |  D     |
 | 103 | kiran       |  R     |
 +-----+-------------+--------+
  

我想要一个产生以下输出的postgresql select Query   (基于id和基于类型的split进行连接。输出必须如此   以下结构)。

+-----+-------------+--------------+
|  ID | EarningName |  DeductName  |
+-----+-------------+--------------+
| 101 | ravi        |   prasad     |
| 101 | rakhav      |   sumesh     |
| 101 | joil        |              |
| 101 | manu        |              |
| 102 | mubi        |   rahul      |
| 102 | sree        |   praveen    |
| 102 | sajeev      |              |
| 102 | ansu        |              | 
| 103 | milin       |   nithin     |
| 103 | abhilash    |   pradeep    |
| 103 | kiran       |   sadham     |
| 103 |             |   rajesh     |
+-----+-------------+--------------+

  I wrote some queries using LEFT JOIN ,But i didn't get like the above structure ..   

1 个答案:

答案 0 :(得分:2)

这比我初想的要复杂。您试图在两列中获得两个列表,它们似乎是无序的。解决方案仍然是条件聚合,但现在您需要一个列来枚举值以及id:

select id,
       max(case when Type = 'R' then name end) as EarningName,
       max(case when Type = 'D' then name end) as DeductName
from (select t.*,
             row_number() over (partition by id, type order by id) as seqnum
      from atablelike t
     ) t
group by id, seqnum;