在SQL中获取标头和项目格式

问题描述 投票:1回答:1

我要求以特定格式排列标题和项目数据。

我有的格式:

Country State
---------------
India   Delhi
India   Gujarat
India   Kerela
US      Texas
US      NJ

国家和州是字段名称

我要求采用以下格式

Country State
---------------
India   
      Delhi
      Gujarat
      Kerela
US  
      Texas
      NJ

这里的概念是,如果标题是相同的,那么它们不应该重复,而该标题的Items应该在下面,而不重复标题数据。

任何人都可以建议我达到这种格式的解决方案。

提前致谢

sql sql-server
1个回答
0
投票

对我来说,问题很不清楚,但你应该在lag()函数的帮助下检查我为上述做了哪些

select (case when lag(A) over (order by A) is null then A else '' end) A,
       (case when lag(B) over (order by B) is null then B else '' end) B,
       (case when lag(C) over (order by C) is null then C else D end) C,
       (case when lag(C) over (order by C) is null then D else E end) D,
       (case when lag(C) over (order by C) is null then E else F end) E,
       (case when lag(C) over (order by C) is null then F else '' end) F
from table t

编辑:首先,正如其他人建议您可以轻松地在应用程序层中这样做,但仍然可以使用SQL(不推荐)

使用row_number()函数为国家/地区分配排名

select 
        case when (row_number() over (partition by Country order by State)) > 1 
             then '' else c.Country 
        end Country,
        t.State
from table t
© www.soinside.com 2019 - 2024. All rights reserved.