求SQL语句 ( 积分: 100 )

  • 主题发起人 主题发起人 gzsuheng
  • 开始时间 开始时间
G

gzsuheng

Unregistered / Unconfirmed
GUEST, unregistred user!
数据表结构如下:
ID Type Price Date
1 A 999.0000 2007-07-01 00:00:00.000
2 A 1999.0000 2007-07-02 00:00:00.000
3 A 2999.0000 2007-07-03 00:00:00.000
4 A 3999.0000 2007-07-04 00:00:00.000
5 B 888.0000 2007-08-13 00:00:00.000
6 B 1888.0000 2007-08-12 00:00:00.000
7 B 2888.0000 2007-08-11 00:00:00.000
8 C 777.0000 2007-09-22 00:00:00.000
9 C 1777.0000 2007-09-21 00:00:00.000

如何拿出下列数据:
ID Type Price Date
1 A 999.0000 2007-07-01 00:00:00.000
5 B 888.0000 2007-08-13 00:00:00.000
8 C 777.0000 2007-09-22 00:00:00.000
 
是查询出每一种Type中ID最小的一条吗?
 
是啊,关键是要拿出记录的ID和Date
 
select a.*,b.price,b.date from
(select min(id) as id,type from 表 group by type) a
left join 表 b
on a.id=b.id and a.type=b.type
 
To:moyiying
抱歉,我录入的数据正好是在同Type中MIN(ID)=MIN(Price),如果是下列情况呢?
不可能做临时表按顺序再生成一遍数据吧[:(]
ID Type Price Date
1 A 2999.0000 2007-07-03 00:00:00.000
2 A 3999.0000 2007-07-04 00:00:00.000
3 A 999.0000 2007-07-01 00:00:00.000
4 A 1999.0000 2007-07-02 00:00:00.000
5 B 2888.0000 2007-08-11 00:00:00.000
6 B 888.0000 2007-08-13 00:00:00.000
7 B 1888.0000 2007-08-12 00:00:00.000
8 C 777.0000 2007-09-22 00:00:00.000
9 C 1777.0000 2007-09-21 00:00:00.000
 
create table uTab(ID int identity,type nvarchar(10),price money,[Date] datetime)
insert into uTab
select 'A',2999.0000,'2007-07-03 00:00:00.000' union all
select 'A',3999.0000,'2007-07-04 00:00:00.000' union all
select 'A',999.0000,'2007-07-01 00:00:00.000' union all
select 'A',1999.0000,'2007-07-02 00:00:00.000' union all
select 'B',2888.0000,'2007-08-11 00:00:00.000' union all
select 'B',888.0000,'2007-08-13 00:00:00.000' union all
select 'B',1888.0000,'2007-08-12 00:00:00.000' union all
select 'C',777.0000,'2007-09-22 00:00:00.000' union all
select 'C',1777.0000,'2007-09-21 00:00:00.000'

select b.* from (
select type,price = min(price)
from uTab
group by type) a left join uTab b on a.type = b.type and a.price = b.price
 
select a.* from
表 a right join (
select type, min(price) as price from 表
group by type
)b
on a.type = b.type and a.price = b.price
 
SELECT *
FROM table
WHERE (price IN
(SELECT MIN(price) AS price
FROM table
GROUP BY type))
 
可不可以查询二次?
1、首先查询出所有的Type
select distinct Type from table
2、根据查询出来的数据,用Delphi再做一个循环,生类似下面的SQL
select * from (select * from table where Type='A' and rownum=1 order by Price,ID)
union all
select * from (select * from table where Type='B' and rownum=1 order by Price,ID)
union all
select * from (select * from table where Type='C' and rownum=1 order by Price,ID)
 
xuefeng_zzg done!
 
多谢各位热心帮忙
 
搞了半天[:D]
可以了:

SELECT DISTINCT [id], type, price, [date]
FROM Table1
WHERE (price IN
(SELECT MIN(price) AS Expr
FROM Table1
GROUP BY type))
--------------
最后可加 order by type/id/date
 

Similar threads

后退
顶部