日期:2014-05-18  浏览次数:20541 次

如何不用union 实现 这条查询的方法
如   男60退休   女50退休   我要查询退休   人员     然不能用union

表如下

name           sex         age
王一           男           55
王二           女           55
丁一           男           65
丁二           女           40

------解决方案--------------------
name sex age
王一 男 55
王二 女 55
丁一 男 65
丁二 女 40

select * from tb where (sex = '男 ' and age > 60) or (sex = '女 ' and age > 55)
------解决方案--------------------
没有问题,主要是看你 > '退休年龄 ' 是否传错值了
select * into t1
from (select '王一 ' as [name], '男 ' as [sex],55 as age
union all
select '王二 ', '女 ',55
union all
select '丁一 ', '男 ',65
union all
select '丁二 ', '女 ',40) A
select * from t1

select * , '退休年龄 ' = case when sex= '男 ' then 60 else 50 end
from t1
where age > 50
drop table t1
------解决方案--------------------
//测试表
create table t1
(
[name] nvarchar(20),
sex nvarchar(20),
birthday datetime
)

insert into t1
values
(
'王一 ',
'男 ',
'03 31 1952 9:20AM '
)
insert into t1
values
(
'王二 ',
'女 ',
'03 31 1952 9:20AM '
)
insert into t1
values
(
'丁一 ',
'男 ',
'03 31 1942 9:20AM '
)
insert into t1
values
(
'丁二 ',
'女 ',
'03 31 1967 9:20AM '
)

//临时表
create table #t2
(
name nvarchar(20),
sex nvarchar(20),
age int
)

insert into #t2
select name, sex , datediff(yy,birthday,getdate())
from t1

//结果
select * from #t2 where (sex = '男 ' and age > 60) or (sex = '女 ' and age > 50)
------解决方案--------------------
select * into t1
from (select '王一 ' as [name], '男 ' as [sex],55 as age
union all
select '王二 ', '女 ',55
union all
select '丁一 ', '男 ',65
union all
select '丁二 ', '女 ',40) A
select * from t1

select * , '退休年龄 ' = case when sex= '男 ' then 60 else 50 end
from t1
where age > (case when sex= '男 ' then 60 else 50 end)
drop table t1