2014-02-26 267 views
0

我有一张表包含来自多个交易的数据,并且我一直试图获取每天,每个客户的最早记录,并调整了我在本网站中看到的其他解决方案(例如this one ),但他们没有为我工作。SQL每天的第一笔交易

交易

 
Time     Id Client  Price  Quantity 
1/2/2013 09:33:20 AM 1 Albert  100.00  5,300 
1/2/2013 10:34:20 AM 2 Albert  100.90  4,800 
1/2/2013 10:34:20 AM 3 Lewis  80.00  25,987 
1/2/2013 11:35:23 AM 4 Benson  251.00   700 
1/2/2013 14:36:20 AM 5 Albert  100.00  2,250 
1/2/2013 15:31:12 AM 6 Albert  99.50  1,340 
1/3/2013 09:33:20 AM 7 Benson  250.00   900 
1/3/2013 15:13:12 AM 8 Benson  250.00   800 
1/3/2013 16:03:55 AM 9 Lewis  80.00  18,890 
1/4/2013 09:01:01 AM 10 Albert  101.00  1,190 
1/4/2013 09:01:01 AM 11 Albert  100.99  98,890 
1/4/2013 09:01:01 AM 12 Lewis  80.98  6,890 
1/4/2013 10:51:00 AM 13 Benson  279.18   190 
1/4/2013 10:51:00 AM 14 Albert  99.36  78,053 
... 

的ID是唯一的,并且也被定义按时间顺序进行排序。时间不是唯一的,这意味着可能有两个交易完全同时发生。

SQL查询需要将拉出第一笔交易的每个客户端一样,每一天,价格和数量,像在一起:

 
Date   Client Price Quantity 
1/2/2013  Albert 100.00  5,300 
1/2/2013  Benson 251.00  700 
1/2/2013  Lewis  80.00 25,987 
1/3/2013  Benson 250.00  900 
1/3/2013  Lewis  80.00 18,890 
1/4/2013  Albert 101.00  1,190 
1/4/2013  Lewis  80.98  6,890 
1/4/2013  Benson 279.18  190 

谁能帮助我该怎么办呢在SQL中?

+0

您正在使用什么数据库? –

+0

数据库在MS Access中,但我很可能会在MySQL –

回答

1

你不指定数据库。所以这是一个普遍的方法。这个想法可以在大多数数据库中使用,但是其中一些功能是不同的。

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 
       ); 
+0

中执行查询。但这不会由客户端分区。 – Blorgbeard

+0

@Blorgbeard。 。 。谢谢。我错过了那个条件。 –

+0

谢谢,出于某种原因,CDATE没有在MS Access中工作,但在MySQL中很顺利.. –

1

在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

相关问题