首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么不用union 实现 这条查询的方法

2012-01-14 
如何不用union 实现 这条查询的方法如男60退休女50退休我要查询退休人员然不能用union表如下namesexage王

如何不用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),
sexnvarchar(20),
birthdaydatetime
)

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
(
namenvarchar(20),
sexnvarchar(20),
ageint
)

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

热点排行