sql 时间问题

来源:百度知道 编辑:UC知道 时间:2024/06/03 02:31:33
名称 数量
1 12
1 35
1 16
1 14
2 36
2 78
2 45
2 47
假设有如上一张表,怎样可以查询同一名称下,数量之差小于10(不是最大减最小,而是最接近的两个数字)的名称.

为了便于书写,名称字段名为NAME,数量字段名为QTY,表名为tablename1
则有:
select *,diff=aqty-bqty from
(
-------------------数值组合子查询
select a.name,aqty=a.qty,bqty=b.qty from
(SELECT name,qty from tablename1) a,
(SELECT name,qty from tablename1) b
where a.name=b.name and a.qty!=b.qty and a.qty-b.qty>=0
-------------------数值组合子查询
) c
where exists

(
select * from
(
select name,mqty=min(aqty-bqty) from
(
-------------------数值组合子查询
select a.name,aqty=a.qty,bqty=b.qty from
(SELECT name,qty from tablename1) a,
(SELECT name,qty from tablename1) b
where a.name=b.name and a.qty!=b.qty and a.qty-b.qty>=0
-------------------数值组合子查询
) d group by name
) e
where e.name=c.name and mqty=c.aqty-c.bqty and mqty<10
)

结果是:
名称 数量1 数量2 差值
name,aqty,bqty,diff
1 16 14 2
1 14 12 2
2 47 45 2

为了便于您理解,您可以将上