首页 > 解决方案 > 如何在 SQL (SQL Server) 中创建垂直组的单个列,其格式与 Excel 对数据透视表所做的一样?

问题描述

我有这样的数据:

来自 Excel Pivot 上的 MS:

在此处输入图像描述

我需要在 SQL Server 中显示我的表中的数据,就像底部窗格中的图像一样。我已经到处搜索了答案。我尝试过 CTE、Pivo​​t、Unpivot、Lag 和其他各种杂项。

除了使用 Excel 或报表在 SSRS 中进行分组之外,我无法以我需要的方式显示数据:

我有两列,地区和商店:

district   store
--------   -----
district1  store1
district1  store2
district2  store3
district2  store4
district2  store5
district3  store6

我用它来获得结果的第一部分:

;with my_locations as
(

    select 
        case 
            when rn = 1 then district
            when rn != 1 not null then ''
        end as district_area
        ,   store
    from (
        select
            ROW_NUMBER() over(partition by district order by district) as rn
        ,   district
        ,   store
        from all_areas  --data from original table
    ) t
) 
select * from my_locations

这给了我:

district   store
--------   -----
district1  store1
NULL       store2
district2  store3
NULL       store4
NULL       store5
district3  store6

但是,我无法将其用于任何看起来像 Excel 枢轴的东西。我想把它放在一个中:

column1
-------
district1
store1
store2
district2
store3
store4
store5
district3
store6

我以为我可以在每个 CASE 之后进行插入,但这不起作用。

标签: sql-serverexcelformattingpivotgrouping

解决方案


我最终使用它来解决它:

    case 
        when rn = 1 then district +  CHAR(13) + CHAR(10) + store
        else store
    end as district_area

完整查询:

;with my_locations as
(

    select 
        case 
            when rn = 1 then district +  CHAR(13) + CHAR(10) + store
            else store
        end as district_area
    from (
        select
            ROW_NUMBER() over(partition by district order by district) as rn
        ,   district
        ,   store
        from all_areas  --data from original table
    ) t
) 
select * from my_locations

我保留了将数据复制到的 CRLF,因此它看起来像我需要的那样。不完全是我想要的,但这是一个问题或格式。


推荐阅读