SQL仅显示第一个值(其中值在列中多次出现)

时间:2016-01-12 16:21:32

标签: sql sql-server

我正在使用sql尝试只在列中多次出现值。 例如,如果我的表看起来像这样,则Age列显示3个年龄为'2'的实例。

Increment | Agenda
-------------------------------------
2         | Minutes Previous Meeting
2         | Minutes Previous Meeting
2         | Minutes Previous Meeting
11        | First Aid
6         | PAT Testing

在这种情况下,我只想显示第一个'2',所以它看起来像这样:

Increment | Agenda
-------------------------------------
2         | Minutes Previous Meeting
          | Minutes Previous Meeting
          | Minutes Previous Meeting
11        | First Aid
6         | PAT Testing

修订:

以下是我正在使用的代码:

SELECT  A.Increment, 
        A.Agenda, 
        MS.Summary, 
        MS.Attendies, 
        MS.Appologies, 
        MS.Department, 
        MS.Date, 
        MS.WhoFor, 
        Ms.WhenFor, 
        MS.Name + ': ' + MS.Date as CreatedBy

            FROM HSAgenda A 
            LEFT OUTER JOIN
            Meeting_summary MS ON A.Increment = MS.Id

            WHERE (A.Increment IN (SELECT SplitValue FROM dbo.Split ((SELECT Agenda FROM Agenda
                                   WHERE AgendaID=@AgendaID  ), ',') AS Split_1)) 
                                   AND (A.Increment <> '1') 
                                   AND (MS.Department = @Department) AND (MS.AgendaId=@AgendaID)

            ORDER BY A.Id, A.Parent

3 个答案:

答案 0 :(得分:2)

WITH cte as (
    SELECT Age,
           Cat,
           ROW_NUMBER() OVER (PARTITION BY Age ORDER BY Cat) as rn
    FROM YourTable
) 
SELECT CASE WHEN rn = 1 THEN Age
            ELSE NULL 
       END as Age,
       Cat
FROM CTE

答案 1 :(得分:1)

奇数请求 - 但尝试使用窗口函数。

SELECT (CASE
            WHEN RowNum <> 1 THEN NULL
               ELSE Age
               END
       ) Age
       ,Cat
FROM 
    (
     SELECT ROW_NUMBER()OVER(PARTITION BY Age ORDER BY Cat) RowNum
           ,Age
           ,Cat
     FROM dbo.YourTable
    ) Inner

答案 2 :(得分:1)

select 
    case 
      when row_number() over (partition by age order by cat) = 1 then age
      else null
    end age,
    cat
  from myTable;