2

I have a query with these results:

A | 1
A | 2
B | 1
B | 2
B | 3

How do I get the results to be like this:

A | 1
  | 2  
B | 1   
  | 2   
  | 3
ekad
  • 14,436
  • 26
  • 44
  • 46
Michael
  • 21
  • 1
  • 2

6 Answers6

4

Here is one way:

SELECT CASE WHEN rn = 1 THEN c1 ELSE NULL END || ' | ' || c2
  FROM (SELECT c1, c2, ROW_NUMBER() OVER (PARTITION BY c1 ORDER BY c2) rn
          FROM your_table);
DCookie
  • 42,630
  • 11
  • 83
  • 92
3

You can use BREAK ON if you are using sqlplus:

SQL> desc tab1;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 COL                                                VARCHAR2(1)
 COL2                                               NUMBER

SQL> select * from tab1;

C       COL2
- ----------
A          1
A          2
B          1
B          2
B          3

SQL> break on col;
SQL> select * from tab1;

C       COL2
- ----------
A          1
           2
B          1
           2
           3

SQL>

More details here.

Lazer
  • 90,700
  • 113
  • 281
  • 364
2

I vaugely remember thereis a way to get this format in SQL PLus.. Another possible way is as given below:

SELECT a.COLUMN_1,
             CASE 
                WHEN a.rnk = 1 THEN a.COLUMN_2 
                ELSE NULL
            END AS COLUMN_2 
  FROM (
                SELECT a.*,
                    RANK() OVER(PARTITION BY COLUMN_1 ORDER BY COLUMN2) rnk
                    FROM <YOUR_TABLE> a
                ) a
Chandu
  • 81,493
  • 19
  • 133
  • 134
1

This presentation requirement is best served in the application you're using to display the results, rather than in the raw SQL. You could meet your requirements with a cursor, but it's not a very elegant solution.

Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
1

This is more of a formatting issue, best solved by whatever you are using to display the output. There's nothing wrong with the query result, as a query result.

FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
1

in oracle, check out the LEAD and LAG functions.

you can look at the previous row, and if it is the same as the current row, change the value to NULL.

Randy
  • 16,480
  • 1
  • 37
  • 55