我有一个通过多个条件执行的查询,结果如下:
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
我需要将结果显示为
a abc a.1
a.2
a.3
a.4
b bad b.1
b.2
b.3
是否可以使用T-SQL?
我正在使用SQL Server 2008-R2。
答案 0 :(得分:1)
您可以使用ROW_NUMBER
的CTE:
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
修改Demo(感谢bluefeet获取数据)
答案 1 :(得分: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
答案 2 :(得分: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;
答案 3 :(得分: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