id 自动编号
name sex date
张三 男 2009-1-12
张三 女 2008-12-1
张三 男 2009-12-1
李四 男 2009-1-12
李四 男 2008-12-1
王五 女 2008-12-1我想要的效果:
比如,条件是SEX=“男”,结果是:
张三 男 2009-1-12
李四 男 2009-1-12条件是date=2008-12-1,结果是:
张三 男 2008-12-1
李四 男 2008-12-1
王五 女 2008-12-1达到这样的效果,SQL该咋写,能给个明确的答案吗?大菜鸟在这么重重叩谢了!
name sex date
张三 男 2009-1-12
张三 女 2008-12-1
张三 男 2009-12-1
李四 男 2009-1-12
李四 男 2008-12-1
王五 女 2008-12-1我想要的效果:
比如,条件是SEX=“男”,结果是:
张三 男 2009-1-12
李四 男 2009-1-12条件是date=2008-12-1,结果是:
张三 男 2008-12-1
李四 男 2008-12-1
王五 女 2008-12-1达到这样的效果,SQL该咋写,能给个明确的答案吗?大菜鸟在这么重重叩谢了!
from ta a
where sex = '男'
group by name,sex
*
from
tb t
where
sex='男'
and
date=(select min(date) from tb where name=t.name and sex=t.sex)
And ([date]=@date or @date is null)
按上表,我用选项设定搜索条件和值,不固定。
如:BianLiang1(某字段),BianLiang2(搜索值)我要的效果是,不管我搜索哪个字段,符合条件的可以是多条,但“Name”要是唯一的!
declare @BianLiang1 varchar(20),@BianLiang varchar(20)
set @BianLiang1='参数'
set @BianLiang2='参数'
if @BianLiang1='sex'
begin
select name,sex,min(date)
from [table]
where sex = @BianLiang2
group by name,sex
end
else
begin
select name,sex,min(date)
from [table]
where date = @BianLiang2
group by name,sex
end
if object_id('[tb]') is not null drop table [tb]
create table [tb](id int identity(1,1),[name] varchar(4),[sex] varchar(2),[date] datetime)
insert [tb]
select '张三','男','2009-1-12' union all
select '张三','女','2008-12-1' union all
select '张三','男','2009-12-1' union all
select '李四','男','2009-1-12' union all
select '李四','男','2008-12-1' union all
select '王五','女','2008-12-1'declare @sex varchar(2),@date datetime
--select @sex = '男'
select @date='2008-12-1'
select * from [tb] t
where [sex]=isnull(@sex,[sex])
and [date]=isnull(@date,[date])
and id = (select min(id) from [tb]
where [name]=t.[name] and [date] = t.[date])
declare @BianLiang1 varchar(20),@BianLiang2 varchar(20)
set @BianLiang1='参数'
set @BianLiang2='参数'
if @BianLiang1='sex'
begin
select name,sex,min(date)
from [table]
where sex = @BianLiang2
group by name,sex
end
else
begin
select name,sex,min(date)
from [table]
where date = @BianLiang2
group by name,sex
end
@BianLiang改成@BianLiang2