使用WHERE子句

时间:2017-01-10 18:04:48

标签: sql ms-access where-clause offset

问题

我想要查询的是我的数据中每个“分组”的第二个结果。例如,带有星号的行。

我试图在[Awardee],[State],[City]上分组,这应该是一个独特的人,我想获得他们的第二个[年]。

OFFSET函数会解决问题,但MS ACCESS在其库中没有。我查找了使用TOP n嵌套查询的变通方法,但在使用变通方法时会产生更多问题。我可以使用某种类型的JOIN语句来完成此操作吗?

样本数据

 ------------------------------------
 |_Awardee_|_State_|_City__|_Year___|
 |  John   |  OH   | Cinci | 2015   |
*|  John   |  OH   | Cinci | 2013   |
 |  John   |  OH   | Cinci | 2011   |
 |  Margret|  IN   | Indy  | 2015   |
*|  Margret|  IN   | Indy  | 2012   |
 |  Margret|  IN   | Indy  | 2011   |
 |  Bob    |  IN   | Indy  | 2011   |
*|  Bob    |  IN   | Indy  | 2010   |
 |  Jeff   |  OH   | Cinci | 2016   |
*|  Jeff   |  OH   | Cinci | 2015   |
 |  Jeff   |  OH   | Cinci | 2013   |
 |  Jeff   |  OH   | Cinci | 2012   |
 |  Susan  |  IN   | Indy  | 2012   |
 |  Spencer|  IN   | Indy  | 2016   |
*|  Spencer|  IN   | Indy  | 2015   |
 -------------------------------------

示例OFFSET解决方法

通过按降序选择前2条记录,然后按升序选择前1条记录,我可以将结果推算为1.

SELECT TOP 1 * FROM 
(SELECT TOP 2 [Awardee], [State], [City], [Year] FROM [Table1]
ORDER BY [Awardee] ASC, [Year] DESC)
ORDER BY [Awardee] ASC, [Year] ASC;

使用SQL

这个SQL查询将获得他们最近的奖励年份(记录只有上面有一个astricks的1行)。但是,正如我们可以看到我是否要使用上面的OFFSET解决方法替换子查询,我最终会得到2个子查询。最内部的子查询将无法在WHERE子句中重新标记“CDFI1”。 MS ACCESS子查询无法看到最近的邻居查询。

SELECT *
FROM [T09a: CDFI Award Records] AS CDFI1
WHERE CDFI1.[ID] IN
(SELECT TOP 1 ID FROM [T09a: CDFI Award Records] as CDFI2
WHERE CDFI2.[Awardee] = CDFI1.[Awardee] AND CDFI2.[City] = CDFI1.[City] AND CDFI2.[ST] = CDFI1.[ST]
ORDER BY CDFI2.[Awardee] ASC, CDFI2.[Year] DESC)
ORDER BY CDFI1.Awardee, CDFI1.Year DESC;

编辑:接受的答案

感谢下面的@krokodilko演示和MYSQL的帮助。为了在ACCESS中工作,有一些小的语法怪癖,主要是使用方括号,如下所示。

SELECT t.[Awardee], t.[ST], t.[City], max( t.[Year] ) as Year
FROM ([T09a: CDFI Award Records] as t
INNER JOIN (
  SELECT [Awardee], [ST], [City], max( [Year] ) as maxYear
  FROM [T09a: CDFI Award Records]
  GROUP BY Awardee, ST, City
) as x
ON x.Awardee = t.Awardee 
  AND x.[ST] = t.[ST]
  AND x.[City] = t.[City]
  AND t.[Year] < x.maxYear)
GROUP BY t.[Awardee], t.[ST], t.[City]

1 个答案:

答案 0 :(得分:1)

我无法访问MS访问权限,但我会使用基本的SQL功能在MySql上进行热门操作:JOIN + GROUP BY + MAX:

SELECT t.Awardee, t.State, t.City, max( t.Year ) as Year
FROM table1 t
JOIN (
  SELECt Awardee, State, City, max( Year ) as Year
  FROM table1
  GROUP BY Awardee, State, City
) x
ON x.Awardee = t.Awardee 
   AND x.State = t.State
   AND x.City = t.City
   AND t.Year < x.year
GROUP BY t.Awardee, t.State, t.City

演示:http://sqlfiddle.com/#!9/690e47/7

我相信你会设法让它在MS Access上运行。