有这样一个表:
养殖户 牛号 配种日期 ........
张三 001 10/02/02
张三 001 10/03/05
李四 002 09/11/25
李四 002 09/12/12
李四 003 10/01/11
因为同一只牛比如张三 001 号牛配种2次 这样的情况很多.我想按照养殖户 ,牛号 来检索每户 里的每头奶牛的最后一次配种日期.应该如何写SQL查询语句. 结果如下:
张三 001 10/03/05
李四 002 09/12/12
李四 003 10/01/11
还有个问题就是 在datagrid控件中 我输入 一条记录后显示在 里面的数据 如何让我刚输入的这条数据显示在最上面
养殖户 牛号 配种日期 ........
张三 001 10/02/02
张三 001 10/03/05
李四 002 09/11/25
李四 002 09/12/12
李四 003 10/01/11
因为同一只牛比如张三 001 号牛配种2次 这样的情况很多.我想按照养殖户 ,牛号 来检索每户 里的每头奶牛的最后一次配种日期.应该如何写SQL查询语句. 结果如下:
张三 001 10/03/05
李四 002 09/12/12
李四 003 10/01/11
还有个问题就是 在datagrid控件中 我输入 一条记录后显示在 里面的数据 如何让我刚输入的这条数据显示在最上面
tb t
where not exists
(select 1 from tb where t.养殖户=养殖户 and t.牛号=牛号 and 配种日期<t.配种日期)
select * from tb t
where not exists(
select 1 from tb
where 养殖户=t.养殖户 and 牛号=t.牛号
and 配种日期>t.配种日期)
select * from tb t
where 配种日期=(
select max(配种日期) from tb
where 养殖户=t.养殖户 and 牛号=t.牛号)
select * from tb t
where 配种日期=(
select top 1 配种日期 from tb
where 养殖户=t.养殖户 and 牛号=t.牛号
order by 配种日期 desc)服务器有问题,写了三条
select * from
tb t
where not exists
(select 1 from tb where t.养殖户=养殖户 and t.牛号=牛号 and t.配种日期<配种日期)
我原来查一条的.现在查的多了不会了
后面的字段都是一些对检索无用的信息.根据这个表所要求的.只能用 养殖户作为索引条件
你只要养殖户和最大日期,你那样写就够了,如果还要个牛号呢?大哥 你说的对 这茬忘了 帮俺解决下呗
where not exists(
select 1 from tb
where 养殖户=t.养殖户 and 牛号=t.牛号
and 配种日期>t.配种日期)
select t.* from tb t where not exists (select 1 from tb where 养殖户 = t.养殖户 and 配种日期 > t.配种日期)
select 养殖户,max(配种日期) from peizhong group by 养殖户,牛号
问题解决了.20楼的疑问不存在了select 养殖户,牛号,配种日期 from tb t
where not exists(
select 1 from tb
where 养殖户=t.养殖户 and 牛号=t.牛号
and 配种日期>t.配种日期)