我有以下数据,我需要使用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
答案 0 :(得分:2)
一种可能的方法是使用如下所示的计数表
; 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