0

我有一个通过多个条件执行的查询,结果如下:

代码 - 名称 - Code2

a     abc     a.1
a     abc     a.2
a     abc     a.3
a     abc     a.4

b     bad     b.1
b     bad     b.2
b     bad     b.3

我需要将结果显示为

代码 - 名称 - Code2

a      abc      a.1
                a.2
                a.3
                a.4

b      bad      b.1
                b.2
                b.3

可以使用 T-SQL 吗?
我正在使用 SQL Server 2008-R2。

4

4 回答 4

1

您可以将 CTE 与ROW_NUMBER

WITH CTE AS
(
   SELECT Code, Name, Code2,
      RN = ROW_NUMBER() OVER (PARTITION BY Code, Name ORDER BY Code2)
   FROM dbo.TableName
   WHERE ....
)
SELECT 
    CASE WHEN RN > 1 THEN '' ELSE Code END AS Code, 
    CASE WHEN RN > 1 THEN '' ELSE Name END AS Name, 
    Code2
FROM CTE

编辑演示(感谢 bluefeet 提供数据)

于 2013-03-15T11:03:41.640 回答
1

您可以使用row_number()来获得结果:

select 
  case when rn = 1 then code else '' end code,
  case when rn = 1 then name else '' end name,
  code2
from
(
  select code, name, code2,
    row_number() over(partition by code, name order by code2) rn
  from table3
) src

请参阅带有演示的 SQL Fiddle

于 2013-03-15T11:03:52.387 回答
0

您可以纯粹在 SQL 中使用row_number()排名来执行此操作:

with val_ranks as (
   select code,name,code2,
       row_number() over (partition by code order by code2) as rown
       from foo
)
select case when rown=1 then code else '' end as code,
       case when rown=1 then name else '' end as name,
       code2
   from val_ranks
   order by code2;

SQLFiddle 示例

于 2013-03-15T11:06:42.680 回答
0

尝试这个 :-

With cte(Col1,col2,col3) as
(
 Select 'a','abc','a.1'
 union all
 Select 'a',    'abc','a.2'
 union all
 Select 'a',    'abc','a.3'
 union all
 Select 'a',    'abc','a.4'
 union all
 Select 'b',    'bad','b.1'
 union all
 Select 'b',    'bad','b.2'
 union all
 Select 'b',    'bad','b.3'
 ),
 cte1 as
(Select * ,  
 row_number() over ( partition by col1,col2 order by (select 0)) as rn 
 from cte
)
 Select case when rn=1 then col1 else null end,
 case when rn=1 then col2 else null end,
 col3
 from cte1
 order by col3
于 2013-03-15T11:08:25.270 回答