如何将单个列值拆分为两列而不使用空值?

时间:2016-10-24 06:15:29

标签: sql postgresql

以下是原始表格。

| Catid| Name  |
| ---- | ----  |
|1     | ramesh|
|1     | suresh|
|1     | mahesh|
|2     | rahul |
|2     | rajesh|

我需要o / p为

|catname1 | catname2|
| ----    | ----    |
|ramesh   | rahul   |
|suresh   | rajesh  |
|mahesh   |         |

我尝试了以下查询,但这会产生空值

select (case when s1.catid=1 then s1.name end) as cat1name,
       (case when s1.catid=2 then s1.name end) as cat2name
from deemucty.sample12 as s1 

2 个答案:

答案 0 :(得分:1)

由于您还没有提供按名称订购的东西,我已按字母顺序排序。

E/time: понедельник-2016/10/24-10:40:54
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err: java.text.ParseException: Unparseable date: "10:40:54" (at offset 0)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at java.text.DateFormat.parse(DateFormat.java:626)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at by.mtz.reminder.wakefulService.NotificationWakefulIntentService.onHandleIntent(NotificationWakefulIntentService.java:58)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at android.os.Looper.loop(Looper.java:137)
10-24 09:27:01.265 2655-3291/by.mtz.reminder W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:60)
10-24 09:27:06.805 2655-3407/by.mtz.reminder D/time: 1477290426

答案 1 :(得分:1)

您可以通过在一个catid中的所有名称与来自其他catid的所有名称之间进行完全外部联接来执行此操作:

select t1.name as catname1, 
       t2.name as catname2
from (
  select name, row_number() over (order by name) as rn
  from the_table
  where catid = 1
) t1
  full join (
    select name, row_number() over (order by name) as rn
    from the_table
    where catid = 2
  ) t2 on t1.rn = t2.rn

示例:http://rextester.com/KJLFAR74695