SQL每天的第一个事务



我有一个表,其中包含许多交易的数据,我一直在努力获得每个客户每天最早的记录,并调整我在这个网站上看到的其他解决方案(比如这个),但它们对我不起作用。

交易表为

TimeId客户端价格数量2013年1月2日上午09:33:20 1阿尔伯特100.00 53002013年1月2日上午10:34:20 2阿尔伯特100.90 48002013年1月2日上午10:34:20 3 Lewis 80.00 259872013年1月2日上午11:35:23 Benson 251.00 7002013年1月2日14:36:20 AM 5阿尔伯特100.00 22502013年1月2日15:31:12 AM 6 Albert 99.50 13402013年1月3日09:33:20 AM 7 Benson 250.00 9002013年1月3日15:13:12 AM 8 Benson 250.00 8002013年1月3日上午16:03:55 Lewis 80.00 188902013年1月4日上午09:01:01 10 Albert 101.00 11902013年1月4日上午11时09:01:01阿尔伯特100.99 988902013年1月4日上午09:01:01 Lewis 80.98 68902013年1月4日上午10:51:00 13 Benson 279.18 1902013年1月4日上午10:51:00 14阿尔伯特99.36 78053…

Id是唯一的,也按定义按时间顺序排序。时间不是唯一的,这意味着可能有两个事务同时发生。

sql查询需要提取每个客户每天进行的第一笔交易,以及价格和数量,类似于:

日期客户价格数量2013年1月2日阿尔伯特100.00 53002013年1月2日Benson 251.00 7002013年1月2日Lewis 80.00 259872013年1月3日Benson 250.00 9002013年1月3日Lewis 80.00 188902013年1月4日阿尔伯特101.00 11902013年1月4日Lewis 80.98 68902013年1月4日Benson 279.18 190

有人能帮我在SQL中做这件事吗?

您没有指定数据库。所以这里有一个通用的方法。这个想法适用于大多数数据库,但有些功能不同。

select cast(t.time as date) as "date", t.*
from transactions t
where not exists (select 1
from transactions t2
where cast(t2.time as date) = cast(t.time as date) and
t2.client = t.client and
t2.id < t.id
);

从时间中获取日期的表达式各不相同。在某些数据库中,这可能是date(time)(MySQL)或trunc(time)(Oracle)或其他数据库。

编辑:

在Access中,这将是:

select CDATE(t.time) as [date], t.*
from transactions t
where not exists (select 1
from transactions t2
where CDATE(t2.time) = CDATE(t.time) and
t2.client = t.client and
t2.id < t.id
);

在MySQL中:

select date(t.time) as "date", t.*
from transactions t
where not exists (select 1
from transactions t2
where date(t2.time) = date(t.time) and
t2.client = t.client and
t2.id < t.id
);

在SQL Server中,应该可以使用类似的方法:

select cast(Time as date), Client, Price, Quantity
from (
select *, row_number() 
over (partition by Client, cast(Time as Date) order by Id) [rn] 
from transactions
) x where x.rn = 1

这里有一个sqlfiddle:http://sqlfiddle.com/#!6/0725d/1

最新更新