T-SQL根据另一个字段返回前一个字段

时间:2014-05-15 00:42:11

标签: sql-server tsql

我很难成功搜索到这一点,因为我还没有想出一个描述我想做什么的搜索字符串,如果已经涵盖了这一点,我会道歉。

我有一张表,其中包含合约编号,开始日期,序列号和日期戳。这些是很多:很多。

我想要实现的目标是返回每个合同编号的开始日期,其中包含最大数量的唯一序列号和最新的日期戳,其中该开始日期有效。

我认为这对T-SQL专家来说是显而易见的,只返回一个具有最多序列号的合同号。谁能告诉我我做错了什么?

SELECT TOP (1) 
   [Contract ID], [Item Begin Date] AS Start_Date, 
   COUNT([Serial Number]) AS CountSerials, 
   Datestamp
FROM
   SourceTable
GROUP BY 
   [Contract ID], [Item Begin Date], Datestamp
HAVING      
   ([Item Begin Date] > CONVERT(DATETIME, '1900-01-01 00:00:00', 102))
ORDER BY 
   CountSerials DESC, Datestamp DESC

干杯, 亚历

2 个答案:

答案 0 :(得分:0)

您可以将其放入临时表中(不使用TOP(1)或oder): 我在这个过程中更改了一些表名,

    if exists (select * from tempdb.sys.tables where name = '##tmp')
  drop table ##tmp

  SELECT * into ##tmp
  from 
  (
  select 
   [Contract_ID], [Begin_Date] AS Start_Date, 
   COUNT([serials]) AS CountSerials, 
   Datestamp
FROM
   SourceTable
GROUP BY 
   [Contract_ID], [begin_date], Datestamp
HAVING      
   [begin_date] > CONVERT(DATETIME, '1900-01-01 00:00:00', 102)
   ) a

   select contract_id,Start_Date, max(countserials) as MAXCOUNT, Datestamp  from ##tmp
   group by contract_id,Start_Date,Datestamp

答案 1 :(得分:0)

您可以使用聚合执行子查询并从中提取所需的结果:

SELECT distinct *
FROM
(
     Select
     [Contract ID], [Item Begin Date] AS Start_Date, 
     COUNT([Serial Number]) OVER(PARTITION BY [Contract ID]) AS CountSerials, 
     datestamp,
     MAX(Datestamp) OVER (PARTITION BY [Contract ID]) maxdatestamp
     FROM
        SourceTable
     WHERE      
        ([Item Begin Date] > CONVERT(DATETIME, '1900-01-01 00:00:00', 102))
) x
WHERE 
datestamp=maxdatestamp