随机取值问题.

--表
DECLARE @T TABLE(ID INT IDENTITY(1,1), GROUP_I INT, VALUE INT, C INT,D INT)
INSERT INTO @T SELECT 1,1.1,NULL,NULL
UNION ALL SELECT 1,1.2,NULL,NULL
UNION ALL SELECT 1,1.3,NULL,NULL
UNION ALL SELECT 1,1.4,NULL,NULL
UNION ALL SELECT 2,1.5,NULL,NULL
UNION ALL SELECT 2,1.6,NULL,NULL
UNION ALL SELECT 2,1.7,NULL,NULL
UNION ALL SELECT 2,1.8,NULL,NULL
UNION ALL SELECT 2,1.9,NULL,NULL
--要求:
1:根据GROUP_I 分组,然后根据C 的最大值,提取该记录.
2:如果分组后C 的最大值有相同的记录,则随机提取一条.
--求相关SQL

Select * from @t as a
where not exists(
Select 1 from @t where GROUP_I=a.GROUP_I and IsNULL(C,0)>IsNULL(a.C,0) 
 ) and ID=(
Select top 1 ID from @t where GROUP_I=a.GROUP_I
 and IsNULL(C,0)=IsNULL(a.C,0) order by NewID()
)

你可能感兴趣的:(sql,c,table,null,insert)