在SQL Server结果中隐藏相同的单元格

时间:2016-08-22 06:40:37

标签: sql sql-server

我有类似这样的表的结果:

id | name | type
---+------+------
1  | John | 1
1  | John | 34
2  | Jane | 2
1  | John | 12
2  | Jane | 168

我需要隐藏重复的值,只允许使用唯一值。我需要得到这样的东西

id | name | type
---+------+------
1  | John | 1
   |      | 34
   |      | 12
2  | Jane | 2
   |      | 168

如何在SQL Server 2012中执行此操作?

2 个答案:

答案 0 :(得分:1)

这是您的表示层应该一般处理的东西,但是......

WITH T AS
(
   SELECT 
         *,
         ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name, Type) AS RN1,
         ROW_NUMBER() OVER (PARTITION BY ID, Name ORDER BY Type) AS RN2
  FROM YourTable
)
SELECT 
      CASE WHEN RN1 = 1 THEN ID END AS ID,
      CASE WHEN RN2 = 1 THEN Name END AS Name,
      Type
FROM T
ORDER BY ID, Name, Type

答案 1 :(得分:0)

如果您需要取消标记的行,则可以使用以下查询:

WITH Src AS
(
    SELECT * FROM (VALUES
        (1, 'John', 1  ),
        (1, 'John', 34 ),
        (2, 'Jane', 2  ),
        (1, 'John', 12 ),
        (2, 'Jane', 168)
    )T(id, name, [type])
)
SELECT
    CASE WHEN RN=1 THEN id END id,
    CASE WHEN RN=1 THEN name END name,
    [Type]
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY id, name ORDER BY [Type]) RN FROM Src) T

它返回:

id          name Type
----------- ---- -----------
1           John 1
NULL        NULL 12
NULL        NULL 34
2           Jane 2
NULL        NULL 168