如何在SQL查询结果中仅保留每组首个customerid,其余重复项置空?
实现重复CustomerID仅保留首个其余置空的SQL方案
当然可以实现,你可以借助SQL的窗口函数ROW_NUMBER()标记每个客户的第一条记录,再根据标记决定是否显示CustomerID。
改造后的完整SQL代码如下:
declare @orderTable table ( customerid int, orderAmt decimal(18,4) ) insert @orderTable values (1,10), (1,20), (1,20), (1,20), (3,10), (3,15), (3,30), (3,10) select case when rn = 1 then customerid else null end as customerid, orderAmt from ( select customerid, orderAmt, ROW_NUMBER() over (partition by customerid order by orderAmt) as rn from @orderTable ) t order by customerid, rn
逻辑说明:
ROW_NUMBER() over (partition by customerid order by orderAmt):按customerid分组(分区),每组内按orderAmt排序,给每条记录分配行号rn,每组第一条记录行号为1。- 外层用
case判断:如果是组内第一条记录(rn=1),显示customerid,否则显示null,即可达成你要的效果。
执行后输出与预期一致:
customerid orderAmt 1 10.0000 NULL 20.0000 NULL 20.0000 NULL 20.0000 3 10.0000 NULL 15.0000 NULL 30.0000 NULL 10.0000
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

