如何使用SQL服务器计算LCM值?



>我有以下数据,我需要使用 T-SQL 查询根据组 ID 计算 LCM(最低计算乘法(值。您的帮助将不胜感激。

Groupid GroupValue
------------------
1        2
1        4
1        6
2        5
2        5
2       10
3        3
3       12
3        6
3        9

预期结果如下。

Groupid   GroupLCM
------------------
1        12
2        10
3        36

一种可能的方法是使用如下所示的计数表

查看工作演示

; with detailedSet as 
(
select 
Groupid,
GroupValue=abs(GroupValue),
biggest=max(GroupValue) over (partition by Groupid),
totalNumbers= count(1) over (partition by Groupid)
from num
)
,   
possibleLCMValues as 
(
select Groupid, counter
from detailedSet b
cross apply 
(
select counter= row_number() over ( order by (select null))  * biggest 
from sys.objects o1 cross join sys.objects o2
)c
where c.counter%GroupValue =0
group by Groupid, counter
having count(1)=max(totalNumbers)
)
,
LCMValues as
(
select 
Groupid,
LCM=min(counter) 
from possibleLCMValues
group by Groupid
)
select * from LCMValues

我找到了我在下面的堆栈流问题中发布的解决方案。在最终结果表中,我们只需再次使用最大值组 id,然后获得 LCM 值。

请注意,就像,我发布此问题以获取更多优化解决方案以删除 for 循环,否则它也使用 for 循环正常工作。

如何在SQL Server中更新没有循环的列?

最新更新