在列中显示记录,仅进行一次分组

时间:2015-03-25 23:31:33

标签: sql sql-server

我有一个基本结构的大表,如:

Aircode  FlightNumber Locator Title
A01      F01          A       Miss
A01      F01          A       Mr
A01      F01          B       Miss
A01      F01          B       Miss
A01      F02          A       Mr
A01      F02          A       Mr
A01      F02          C       Mr
A02      F01          A       Mr

我想知道是否可以创建查询并在MSSQL中只返回一次组名,例如:

Aircode  FlightNumber Locator Title
A01      F01          A       Miss
                              Mr
                      B       Miss
                              Miss
         F02          A       Mr
                              Mr
                      C       Mr
A02      F01          A       Mr

在一些搜索之后我找到了使用Row_Number()Over(Partition by)的方法,但在这种情况下我对多个组感到非常困惑,因为我想不出从多列隐藏多个值的方法。我想知道是否有适当的方法来处理这一数据。

编辑1 通过应用CTE和ROW_NUMBER方法,它首先返回没有值的空白记录,然后返回标题,定位器等。示例:

Aircode  FlightNumber Locator Title


                              Miss
                              Miss
                      A       Mr
 A01       F01        B       Miss
 A02       F02        B       Miss

1 个答案:

答案 0 :(得分:5)

尝试为每个分区级别分配ROW_NUMBER,并仅显示第一个分区的文本:

WITH cte AS (
  SELECT
     [Aircode]
    ,[FlightNumber]
    ,[Locator]
    ,[Title]
    ,[r1] = ROW_NUMBER() 
               OVER(PARTITION BY [Aircode] 
                    ORDER BY [AirCode])
    ,[r2] = ROW_NUMBER() 
               OVER(PARTITION BY [Aircode], [FlightNumber] 
                    ORDER BY [FlightNumber])
    ,[r3] = ROW_NUMBER() 
               OVER(PARTITION BY [Aircode], [FlightNumber], [Locator]
                    ORDER BY [Locator])
  FROM <table>
)
SELECT  [Aircode]      = CASE WHEN [r1] = 1 THEN [Aircode] ELSE '' END
       ,[FlightNumber] = CASE WHEN [r2] = 1 THEN [FlightNumber] ELSE '' END
       ,[Locator]      = CASE WHEN [r3] = 1 THEN [Locator] ELSE '' END
       ,[Title]
FROM cte
ORDER BY cte.[Aircode], cte.[FlightNumber], cte.[Locator], cte.[Title]