简体   繁体   中英

Group Numbers based on Level

I have requirement in SQL Server database where I have to group the data. please find the image attached for reference.

If the Level is more than 2 then it has to be grouped under level 2 (ex: 1.1.1, 1.1.2 are rolled up under 1.1.) and if there isn't any level 2 available then have to create a second level based on the level 3 Numbers (ex: 1.2.1)

Thanks

Would this do, if you need the new values as computed columns?
: this works with double digits and the third column is null for 1st/2nd level version:这适用于两位数,第 1/2 级版本的第三列为空

CREATE TABLE Test
(
    Version varchar(30),
    VersionMain AS CASE
        WHEN CHARINDEX('.',Version,4) > 0 THEN LEFT(Version,CHARINDEX('.',Version,4)) ELSE Version END,
    VersionSub AS CASE
        WHEN LEN(Version) - LEN(REPLACE(Version,'.','')) >= 3 THEN Version ELSE NULL END
)

you can use CHARINDEX to locate '.' and then decide DERIVED_COL_2.

SELECT COLUMN, 
SUBSTRING(COLUMN,1,4)DERIVED_COL_1,
CASE WHEN CHARINDEX('.',COLUMN,5) = 6 THEN COLUMN END AS DERIVED_COL_2
FROM YOUR_TABLE

If it's not certain that the first 2 numbers are single digits:

declare @T table ([Column] varchar(20));

insert into @T values ('1'),('1.2.'),('1.2.3.'),('1.2.3.4.'),('10.20.'),('10.20.30.'),('10.20.30.40.');

select 
case when [Column] like '%.%.%' then substring([Column],1,charindex('.',[Column],charindex('.',[Column])+1)) else [Column] end as [Derived Col1], 
case when [Column] like '%.%.%.%' then [Column] else '' end as [Derived Col2]
from @T;

If it's certain that the first 2 numbers are single digits then it can be simplified:

declare @T table ([Column] varchar(20));

insert into @T values ('1'),('1.2.'),('1.2.3.'),('1.2.3.4.');

select 
substring([Column],1,4) as [Derived Col1], 
case when [Column] like '%.%.%.%' then [Column] else '' end as [Derived Col2]
from @T;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM