SQL的等价于First

时间:2014-04-14 14:47:54

标签: sql-server

据我所知,没有一个与访问功能相同的等价物,所以我实际上只是在寻找帮助来编写查询来执行相同的任务。基本上,这是我到目前为止所做的:

SELECT PR.SSN as SSN, 
    MIN(PR.[Last Name]) as [Last Name],
    MIN(PR.Address) as [Address], 
    MIN(PR.City) as [City], 
    MIN(PR.State) as [State], 
    MIN(PR.Zip) as [Zip],
    MIN(cast(PR.[Pay Begin Period] as date)) as [Pay Begin Period],
    MAX(cast(PR.[Pay End Period] as date)) as [Pay End Period],
FROM Payroll.dbo.[Table1] PR
WHERE (cast(PR.[Pay Begin Period] as date) > '1/1/2013' AND
        cast(PR.[Pay End Period] as date) < '12/31/2013')
GROUP BY PR.SSN

此查询将检索每个SSN的最早[支付开始期]和最新[支付结束期]。但是,我希望检索到的[姓氏]来自最早的[支付开始期]。在某些情况下,人们会有[姓氏]更改。我们只希望记录最早/第一个。

所以我想改变这一行:

MIN(PR.[Last Name]) as [Last Name],

这样的事情:

(SELECT [Last Name] 
 FROM Payroll.dbo.[Table1] 
 WHERE [Pay Begin Period] = Min([Pay Begin Period])),

我意识到这不起作用,但这是我能解释我所寻找的最佳方式。

1 个答案:

答案 0 :(得分:4)

在SQL Server中,您可以通过枚举每个SSN的行然后选择第一行来执行此操作:

SELECT PR.SSN as SSN, 
    MAX(CASE WHEN seqnum = 1 THEN PR.[Last Name] END) as [Last Name],
    MIN(PR.Address) as [Address], 
    MIN(PR.City) as [City], 
    MIN(PR.State) as [State], 
    MIN(PR.Zip) as [Zip],
    MIN(cast(PR.[Pay Begin Period] as date)) as [Pay Begin Period],
    MAX(cast(PR.[Pay End Period] as date)) as [Pay End Period],
FROM (SELECT pr.*,
             ROW_NUMBER() OVER (PARTITION BY PR.SSN ORDER BY [Pay Begin Period]) as seqnum
      FROM Payroll.dbo.[Table1] PR
     ) pr
WHERE (cast(PR.[Pay Begin Period] as date) > '1/1/2013' AND
        cast(PR.[Pay End Period] as date) < '12/31/2013')
GROUP BY PR.SSN;

row_number()是一个排名函数,用于为组内的行分配序号。该组由partition by子句定义,因此每个SSN值都有自己的数字序列。排序由ORDER BY子句指定。