case when 的有关问题
case when 的问题
有一张表 A 里面 有以下字段:
rm,gs,wgs,xh,xh1
xh 对应的是 gs 按数字大小从 1往后排序的号码
xh1 对应的是 wgs 按数字大小从1往后排序的号码
rm有重复的,重复需要把他们的对应数字都加起来。
查出序号(xh,xh1)排得不对
如一下数据:
rm,gs,wgs,xh,xh1
小明,200,100 ,1,2
小明,70 ,70 ,1,2
小华,180,180, 2,1
小红, 170,110,4,4
小丁, 160,110 3,5
小小, 150,100 5,3
提出排序不对的数据应该是下面:
小红, 170,110,4,3
小丁, 160,110 3,4
小小, 150,100 5,3
------解决方案--------------------
有一张表 A 里面 有以下字段:
rm,gs,wgs,xh,xh1
xh 对应的是 gs 按数字大小从 1往后排序的号码
xh1 对应的是 wgs 按数字大小从1往后排序的号码
rm有重复的,重复需要把他们的对应数字都加起来。
查出序号(xh,xh1)排得不对
如一下数据:
rm,gs,wgs,xh,xh1
小明,200,100 ,1,2
小明,70 ,70 ,1,2
小华,180,180, 2,1
小红, 170,110,4,4
小丁, 160,110 3,5
小小, 150,100 5,3
提出排序不对的数据应该是下面:
小红, 170,110,4,3
小丁, 160,110 3,4
小小, 150,100 5,3
------解决方案--------------------
- SQL code
declare @T table (rm varchar(4),gs int,wgs int,xh int,xh1 int) insert into @T select '小明',200,100,1,2 union all select '小明',70,70,1,2 union all select '小华',180,180,2,1 union all select '小红',170,110,4,4 union all select '小丁',160,110,3,5 union all select '小小',150,100,5,3 ;with maco as ( select rm,sum(gs) gs,sum(wgs) wgs from @T group by rm ) select c.* from ( select *, xh=(select count(1) from maco where gs>=a.gs), xh1=(select count(1) from maco where wgs>=a.wgs) from maco a ) b left join @T c on b.rm=c.rm and (b.xh<>c.xh or b.xh1<>c.xh1) where c.rm is not null /* rm gs wgs xh xh1 ---- ----------- ----------- ----------- ----------- 小丁 160 110 3 5 小红 170 110 4 4 小小 150 100 5 3 */