sql-server - 如何在 SQL (SQL Server) 中创建垂直组的单个列,其格式与 Excel 对数据透视表所做的一样?
问题描述
我有这样的数据:
来自 Excel Pivot 上的 MS:
我需要在 SQL Server 中显示我的表中的数据,就像底部窗格中的图像一样。我已经到处搜索了答案。我尝试过 CTE、Pivot、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 之后进行插入,但这不起作用。
解决方案
我最终使用它来解决它:
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,因此它看起来像我需要的那样。不完全是我想要的,但这是一个问题或格式。
推荐阅读
- android - Android 风格签名未按预期工作
- python - django-storages + factoryboy:TypeError:预期的字符串或类似字节的对象
- c# - Xamarin Forms 等待图像被保存并显示
- c# - 如何防止通过 ASP.NET Core Web API 中的模型绑定设置属性?
- java - 无法切换到 Selenium 中的帧,并在下面的描述中给出了详细信息
- gradle - 如何在自定义 gradle 插件中创建 .jar 文件?
- c# - 在 Umbraco 8 中从 JToken 渲染网格布局
- reactjs - 如何使用对 SharePoint 列表的 pnp.sp.web REST 调用过滤检索到的项目
- android - 没有任何高度 wrap_content 的子视图的约束布局采用完整的父高度
- javascript - 更改默认文本材质表