I have a CSV file with 2 columns .
Empid | SID
:-----|-----:
12312 | S-1-5-21-3751615294
12312 | S-1-5-21-3751615298
12312 | S-1-5-21-3751615292
12313 | S-1-5-21-3751615294-5078
13546 | S-1-5-21-3751615294-50725
12312 | S-1-5-21-3751615291
14151 | S-1-5-21-3751615294-50722
For an Empid there are multiple SIDs available .I need help writing a sql SELECT query that can map(and store) these SIDs(sorted) into multiple columns.
Desired SQL Select output is below :-
+--------+---------------------------+---------------------+--------------------+--------------------+
| Empid | SID1 | SID2 | SID3 | SID4 |
+--------+---------------------------+---------------------+--------------------+--------------------+
| 12312 | S-1-5-21-3751-65291 | S-1-5-21-375165292 | S-1-5-21-375165294 | S-1-5-21-375165298 |
| 12313 | S-1-5-21-3751615294-5078 | NULL | NULL | NULL |
| 13546 | S-1-5-21-3751615294-50725 | NULL | NULL | NULL |
+--------+---------------------------+---------------------+--------------------+--------------------+
I am collecting an employee record in my application collector(using sql select queries) from a CSV file and need to collect these SIDs in his record .Maximum 4 SIDs can be possible so I created 4 attributes for SIDs .
Thanks in advance .
Presumably, you know the number of columns. If so, you can do it using conditional aggregation and row_number()
:
select empid,
max(case when seqnum = 1 then sid end) as sid_1,
max(case when seqnum = 2 then sid end) as sid_2,
max(case when seqnum = 3 then sid end) as sid_3,
max(case when seqnum = 4 then sid end) as sid_4
from (select t.*, row_number() over (partition by empid order by empid) as seqnum
from t
) t
group by empid;
If you don't know the number, then perhaps a comma-delimited list will do:
select empid, listagg(sid, ',') within group (order by sid) as sids
from t
group by empid;
A SQL query has a fixed number of columns, so a result set that has a flexible number of columns would require dynamic SQL.
You can use window function row_number()
to assign row number to sid within each empid and then use conditional aggregation to get the final results.
select
empid,
min(case when rn = 1 then sid end) sid1,
min(case when rn = 2 then sid end) sid2,
min(case when rn = 3 then sid end) sid3,
min(case when rn = 4 then sid end) sid4
from (select
t.*,
row_number() over (partition by empid order by sid) rn
from table t) group by empid;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.