[英]Group Numbers based on Level
I have requirement in SQL Server database where I have to group the data.我对 SQL Server 数据库有要求,我必须在其中对数据进行分组。 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)如果级别大于 2,则必须将其分组在级别 2 下(例如:1.1.1、1.1.2 汇总在 1.1 下。),如果没有任何级别 2 可用,则必须创建第二个级别基于第 3 级数字(例如:1.2.1)
Thanks谢谢
Would this do, if you need the new values as computed columns?如果您需要将新值作为计算列,这样做可以吗?
Updated : 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 '.'您可以使用 CHARINDEX 来定位 '.' and then decide DERIVED_COL_2.
然后决定 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:如果不确定前 2 个数字是个位数:
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:如果确定前 2 个数字是个位数,则可以简化:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.