日期:2014-05-17  浏览次数:20649 次

这样的查询如何写
------------------------------
品名  单价  地域别
a     10    1
a     11    2
b     5     1
b     4     2
c     3     1
d     6     2

想要的结果:
如果给条件是True则显示:
------------------------------
品名  单价  地域别
a     10    1
b     5     1
c     3     1
d     6     2
如果给条件是False则显示:
------------------------------
品名  单价  地域别
a     11    2
b     4     2
c     3     1
d     6     2

就是说:①如果条件为真,同一种品名有两种单价就显示地域别为1的单价,
          一种品名只有一种单价就不考虑地域别
        ②如果条件为假,同一种品名有两种单价就显示地域别为2的单价,
          一种品名只有一种单价就不考虑地域别

------解决方案--------------------

--true
;with a1 (品名,单价,地域别) as
(
select 'a',10,1 union all 
select 'a',11,2 union all 
select 'b',5,1 union all 
select 'b',4,2 union all 
select 'c',3,1 union all 
select 'd',6,2
)
,a2 as
(
select *,row_number() over(partition by 品名 order by 地域别) re from a1
)
select 品名,单价,地域别
from a2 
where re=1

--False
;with a1 (品名,单价,地域别) as
(
select 'a',10,1 union all 
select 'a',11,2 union all 
select 'b',5,1 union all 
select 'b',4,2 union all 
select 'c',3,1 union all 
select 'd',6,2
)
,a2 as
(
select *,row_number() over(partition by 品名 order by 地域别 desc) re from a1
)
select 品名,单价,地域别
from a2 
where re=1

------解决方案--------------------

create table kc
(品名 varchar(5),单价 int,地域别 int)

insert into kc
 select 'a',10,1 union all
&