另一种写法:select *,case when exists(select 1 from @1 where a=tem.a) then isnull((select c from @1 where a=tem.a and b=tem.b1),isnull((select c from @1 where a=tem.a and b=tem.b2),(select c from @1 where a=tem.a and b='所有'))) else isnull((select c from @1 where a='所有' and b=tem.b1),isnull((select c from @1 where a='所有' and b=tem.b2),(select c from @1 where a='所有' and b='所有'))) end from @2 tem
case when exists (select c from @1 where a=tem.a) then
case when exists (select c from @1 where a=tem.a and b=tem.b1) then
isnull((select c from @1 where a=tem.a and b=tem.b1),(select c from @1 where a=tem.a and b='所有'))
else
isnull((select c from @1 where a=tem.a and b=tem.b2),(select c from @1 where a=tem.a and b='所有'))
end
else
case when exists (select c from @1 where a='所有' and b=tem.b1) then
isnull((select c from @1 where a='所有' and b=tem.b1),(select c from @1 where a='所有' and b='所有'))
else
isnull((select c from @1 where a='所有' and b=tem.b2),(select c from @1 where a='所有' and b='所有'))
end
end as c
from @2 tem
exists(select 1 from @1 where a=tem.a)
then isnull((select c from @1 where a=tem.a and b=tem.b1),
isnull((select c from @1 where a=tem.a and b=tem.b2),
(select c from @1 where a=tem.a and b='所有')))
else isnull((select c from @1 where a='所有' and b=tem.b1),
isnull((select c from @1 where a='所有' and b=tem.b2),
(select c from @1 where a='所有' and b='所有')))
end from @2 tem这句和登山团长的意思是一样的,估计效率差不多!
order by case
when a=tem.a and b=tem.b1 then 1
when a=tem.a and b=tem.b2 then 2
when a=tem.a and b='所有' then 3
when a='所有' and b=tem.b1 then 4
when a='所有' and b=tem.b2 then 5
when a='所有' and b='所有' then 6
else 7 end)
from @2 tem
order by case
when a=tem.a then (case when b=tem.b1 then 1
when b=tem.b2 then 2
when b='所有' then 3 end)
when a='所有' then (case when b=tem.b1 then 4
when b=tem.b2 then 5
when b='所有' then 6 end)
else 7 end)
from @2 tem
---------- ---------- ---------- -----------
大类1 小类1_1 小类2_1 3
大类1 小类1_2 小类2_1 1
大类1 小类1_4 小类2_2 2
大类1 小类1_2 小类2_3 2
大类2 小类1_2 小类2_1 5
大类1 小类1_6 小类2_1 1
大类7 小类1_7 小类2_1 5
大类4 小类1_12 小类2_3 5
order by case
when a=tem.a then (case when b=tem.b1 then 1
when b=tem.b2 then 2
when b='所有' then 3 else 7 end)
when a='所有' then (case when b=tem.b1 then 4
when b=tem.b2 then 5
when b='所有' then 6 else 7 end)
else 7 end)
from @2 tema b1 b2
---------- ---------- ---------- -----------
大类1 小类1_1 小类2_1 1
大类1 小类1_2 小类2_1 2
大类1 小类1_4 小类2_2 3
大类1 小类1_2 小类2_3 4
大类2 小类1_2 小类2_1 6
大类1 小类1_6 小类2_1 2
大类7 小类1_7 小类2_1 7
大类4 小类1_12 小类2_3 9