每组行获取最新的2个值SQL Server 2000

时间:2015-10-02 13:59:00

标签: sql sql-server tsql sql-server-2000

所以我已经梳理了多页stackoverflow问题,看起来我一直在接近但是没有得到我需要的确切结果......所以我已经屈服于提交这个问题。

首先,这是在SQL Server 2000服务器上......我知道这很糟糕。

我有两个表在一个SQL查询中链接在一起,总体上是相当基本的。示例数据如下: Current Results

我用来获取该数据的查询是:

SELECT DISTINCT
AH.locationid as locationid
,AH.adate as date
,Min( CASE WHEN Asum.code = '201' THEN Amount END ) AS attrib1
,Min( CASE WHEN Asum.code = '204' THEN Amount END ) AS attrib2
,Min( CASE WHEN Asum.code = '206' THEN Amount END ) AS attrib3
,Min( CASE WHEN Asum.code = '212' THEN Amount END ) AS attrib4
,Min( CASE WHEN Asum.code = '215' THEN Amount END ) AS attrib5
,Min( CASE WHEN Asum.code = '218' THEN Amount END ) AS attrib6
,Min( CASE WHEN Asum.code = '221' THEN Amount END ) AS attrib7
,Min( CASE WHEN Asum.code = '231' THEN Amount END ) AS attrib8
,AH.checkid as checktype
FROM [asum] ASum

INNER JOIN [Ahead] AH
ON  Asum.AID = AH.AID

WHERE AH.code IN ('212','201','206','204','215','218','221','231')

AND AH.checkid <> 'c'
AND AH.checkid <> 'b'

GROUP BY 
 AH.code
,ASum.amount
,AH.adate
,AH.checkid

ORDER BY 
 AH.locationid
,AH.adate
,attrib1
,attrib2
,attrib3
,attrib4
,attrib5
,attrib6
,attrib7
,attrib8
,AH.checkid'

所以我要做的是返回每个位置的最新两个日期以及最新两个日期的所有attrib。

所以我基本上试图得到这样的东西: Wanted Results

我最接近的是将以下内部联接代码添加到查询中,这让我只是最关键​​的日期...我面临的问题是如何从这个子查询获得两个最大日期,我内心也是。< / p>

  INNER JOIN (SELECT 
                locationid,
                MAX(adate) as newest

             FROM   ahead

             GROUP BY locationid) t1
 ON t1.locationid = AH.locationid
 AND t1.newest = AH.adate

因此,通过内部联接,我只需获得每个位置ID中的一个而不是每个位置ID中的两个,就像我需要的那样。粗略的部分是这是在SQL Server 2000数据库... UGH。

非常感谢您提出任何建议/建议!

1 个答案:

答案 0 :(得分:5)

我无法测试它,因为我没有SQL Server 2000,但我认为这可能有效:

 INNER JOIN (SELECT a1.locationid,
                    MAX(a1.adate) as newest,
                    MAX(a2.adate) as second_newest
               FROM ahead a1
               JOIN ahead a2
                 ON a2.locationid = a1.locationid
                AND a2.adate < a1.adate
              GROUP BY a1.locationid) t1
ON t1.locationid = AH.locationid
AND (t1.newest = AH.adate OR t1.second_newest = AH.adate)

编辑:看看John Bollinger的评论,我应该补充一点,如果(locationid, adate)组合是唯一的,我只希望这可行。