两个表,表头表和表体表。取表头表里的最大时间,max(cmaketime)的单据id通过这个id,取物料的表体的单价,两个表是通过id关联的,问下sql怎么写,谢谢!
解决方案 »
- 存储过程中传入参数问题 求高手解答
- 关于MSSQL 2005开启WAE
- 我的服务器,数据库sql server 2000 出现3704的错误,你遇到过吗?就是运行一段时间就出错,只能重启。
- SQL统计查询
- 在SQL数据库中有没有一个象Access一样的id是自动编号的字段类型
- 存储过程的简单问题?
- 如何从getdate()获得yymmddhhmmss这个时间呢?
- 关于数据库复制崩溃的问题
- ms sql server怎样取的数据库的第一行数据或最后一行数据?
- 关于存储过程的冲突问题
- 能否用一条Update语句完成拷贝上一条记录的值?
- 想学习sql server 2005数据库,推荐下有哪些经典书籍
select [单价] from [表体] where exists(select 1 from [表头] where [表头].[id]=[表体].[id])
--> 测试数据:@T
declare @表头 table([id] int,[cmaketime] int)
insert @表头
select 1,6 union all
select 1,7 union all
select 1,8 union all
select 2,12 union all
select 2,13 union all
select 2,14 union all
select 3,25 union all
select 3,26 union all
select 3,28--> 测试数据:@表体
declare @表体 table([id] int,[单价] int)
insert @表体
select 1,3 union all
select 2,5 union all
select 3,6select
*,(select max([cmaketime]) from @表头 where id=t.id) as [cmaketime]
from @表体 t
/*
id 单价 cmaketime
----------- ----------- -----------
1 3 8
2 5 14
3 6 28
*/
select a.[单价] from [表体] a,(select top 1 [id],max([maketime]) from [表头] group by [id] order by max([maketime]) desc) b where a.[id]=b.[id]
--> 测试数据:@表体
declare @表体 table([id] int,[物料编码] int,[单价] int)
insert @表体
select 1,11,3 union all
select 2,11,5 union all
select 3,12,6然后应该是这样的
11,5
12,6
select a.[单价]
from [表体] a,
(select top 1 [id],max([maketime]) from [表头] group by [id] order by max([maketime]) desc) b
where a.[id]=b.[id]
select * from
[表头表]a
left join [表体表]b
on a.id=b.id
where
b.id=(select top 1 [id] from [表头表] group by [id] order by max([maketime]) desc)