TSQL选择每个合同的第一个和最后一个条目

时间:2017-07-17 08:02:01

标签: sql tsql sybase

我有一个历史表,每次更改合同表时都会写入。现在我必须知道每份合同的第一个和最后一个条目。我有一个可以加入的所有合同的帮助。

表sk_vps_all

中的示例数据
contract_id, lastchange, other_id(ignore this)
   39865537 21 Oct 2014 12:15:03.073PM       8386311
   39865537 21 Nov 2014 19:55:55.363PM       8386311
   39865537 21 Nov 2014 20:02:22.176PM       8386311
   39865537 21 Nov 2014 20:13:30.236PM       8386311
   39865537 27 Nov 2014 14:59:34.900PM       8386311
   39865537 27 Nov 2014 14:59:45.973PM       8386311
   39865537  2 Aug 2016 12:42:31.570PM       8386311
   39868261 20 Feb 2006 21:31:44.533PM          NULL
   39868261 20 Feb 2006 21:31:44.550PM          NULL
   39868261 20 Feb 2006 21:31:44.616PM          NULL
   39868261 20 Feb 2006 21:36:42.026PM       8388985
   39868261 20 Feb 2006 21:41:32.030PM       8388985
   39868261 20 Feb 2006 22:01:16.843PM       8388985
   39868261  3 Aug 2010 21:34:13.030PM       8388985
   39869226 21 Feb 2006 02:36:37.173AM          NULL
   39869226 21 Feb 2006 02:36:37.186AM          NULL
   39869226 21 Feb 2006 02:36:37.376AM          NULL
   39869226 21 Feb 2006 02:41:06.043AM       8389959
   39869226 21 Feb 2006 03:11:18.793AM       8389959
   39869226 21 Feb 2006 03:26:22.356AM       8389959
   39869226 21 Feb 2006 09:17:16.553AM       8389959
   39869226 15 Oct 2008 02:08:42.213AM       8389959
   39869226 15 Oct 2008 10:18:24.930AM       8389959
   39869226 17 Nov 2008 01:13:16.586AM       8389959
   39869226 17 Nov 2008 09:01:57.410AM       8389959
   39869226 19 Jan 2009 00:54:44.686AM       8389959
   39869226 19 Jan 2009 09:31:15.926AM       8389959
   39869226 26 Jan 2009 01:04:50.330AM       8389959
   39869226 27 Jan 2009 10:33:19.910AM       8389959
   39869226 14 Jun 2010 02:07:56.230AM       8389959
   39869226 14 Jun 2010 10:03:24.626AM       8389959

我试过这个,

select min(o.contract_id), min(o.lastchange), max(o.lastchange)  
from operators..sk_vps_all o, operators..sk_vps_ta a  
where o.contract_id = a.contract_id;

结果只有一行,而不是全部。

获取每份合同的第一行和最后一行数据的任何想法。 我必须在sybase RDMBS

上使用TSQL执行此操作

1 个答案:

答案 0 :(得分:1)

SELECT o.contract_id
,min(o.lastchange)
,max(o.lastchange)
FROM operators..sk_vps_ta a
LEFT JOIN operators..sk_vps_all o ON o.contract_id = a.contract_id
GROUP BY o.contract_id