每个匹配仅显示第一行

时间:2012-01-25 12:54:04

标签: sql ms-access group-by

我有一个表(AreaPartners),我想只匹配每个组中的第一个“名称”记录,按“ID”排序,按“区域”分组。所以对于下表:

    Area    Name            ID
    AB      ISmith          748
    AB      AWood           750
    AB      HArcher         751
    AB      DMunslow        753
    AB      DCornelius      754
    BH      MLee            301
    BH      NMcClean        307
    BH      DMiles          309
    BH      LPayze          325
    BH      MPinnock        329

我想要为AB返回结果ISmith,为BH返回MLee。

我该怎么做呢?我相信它与Group By功能有关,但我不能让我的生活让它发挥作用。

2 个答案:

答案 0 :(得分:6)

试试这个:

SELECT yourTable.Area, yourTable.Name
FROM yourTable INNER JOIN (
  SELECT MIN(Id) AS MinId
  FROM yourTable
  GROUP BY Area) M ON yourTable.Id = M.MinId

答案 1 :(得分:1)

因注释而更新(没有表变量,分区不是MS访问语句)。您也可以使用IN声明执行此操作:

SELECT 
    yourTable.Area, 
    yourTable.Name
FROM yourTable 
WHERE yourTable.Id IN
(
    SELECT 
        MIN(tbl.Id) AS MinId
    FROM 
        yourTable as tbl
    GROUP BY 
        tbl.Area
)

在MSSQL中你可以这样写:

DECLARE @tbl TABLE
    (
        Area VARCHAR(100),
        Name VARCHAR(100),
        ID INT
    )
INSERT INTO @tbl
SELECT 'AB','ISmith',748
UNION ALL
SELECT 'AB','AWood',750
UNION ALL
SELECT 'AB','HArcher',751
UNION ALL
SELECT 'AB','DMunslow',753
UNION ALL
SELECT 'AB','DCornelius',754
UNION ALL
SELECT 'BH','MLee',301
UNION ALL
SELECT 'BH','NMcClean',307
UNION ALL
SELECT 'BH','DMiles',309
UNION ALL
SELECT 'BH','LPayze',325
UNION ALL
SELECT 'BH','MPinnock',325
;WITH CTE
AS
(
SELECT
    RANK() OVER(PARTITION BY tbl.Area ORDER BY ID) AS iRank,
    tbl.ID,
    tbl.Area,
    tbl.Name
FROM
    @tbl AS tbl
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.iRank=1