SQL Pivot with multiple values(具有多个值的 SQL Pivot)
问题描述
你好,我有一张这样的桌子:
Hello I have a table like so:
Building Categories Properties
-----------------------------------------
Building250 Structure Steel
Building250 Security Access Card
Building250 Security Security Guard
Building250 Security Fire Alarm System
Building250 Security Sprinklered
Building250 Security Smoke or heat detectors
Building46 Structure Brick
Building46 Structure Steel
Building46 Walls Steel Stud
Building46 Walls Masonry
Building46 Washroom OwnSpace
Building46 Washroom Common
Building46 Security Access Card
Building46 Security Burglar Alarm
我需要像这样旋转它:
Building Structure Security Walls Washroom
----------------------------------------------------------------------------
Building250 Steel Access Card
Security Guard
Fire Alarm System
Sprinklered
heat detectors
Building46 Brick Access Card Steel Stud OwnSpace
Steel Burglar Alarm Masonry Common
Sprinklered
我尝试了 SQL Pivot,但由于它需要聚合,因此它只返回给定类别的 1 个属性.还有其他方法吗?
I tried SQL Pivot, but since it requires an aggregation, it returns only 1 property for a given category. Is there another way?
这是我的 Pivot SQL:
Here's my Pivot SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Category)
FROM Buildings
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Building, ' + @cols + ' from
(
SELECT Building, Category, Property, from Buildings
) x
pivot
(
min(Property)
for Category in (' + @cols + ')
) p '
execute(@query)
推荐答案
正如您所指出的,Pivot 可以进行聚合,虽然有可能的解决方法,但您可以通过以下方式在不使用 pivot 的情况下完成您需要的工作.您也可以使用与制作动态枢轴相同的方法使其动态化.
As you noted Pivot can do aggregation and while there are workarounds possible you can accomplish what you need without pivot with something like the following. You could also make it dynamic using the same method you would make a dynamic pivot.
Select B.Building, Str.Properties Structure,
Sec.Properties Security, Walls.Properties Walls, Wash.Properties Washroom
From (Select Distinct Building From Table) B
Left Join Table Str On Str.Building = B.Building And Categories = 'Structure'
Left Join Table Sec On Sec.Building = B.Building And Categories = 'Security'
Left Join Table Walls On Walls.Building = B.Building And Categories = 'Walls'
Left Join Table Wash On Wash.Building = B.Building And Categories = 'Washroom'
这篇关于具有多个值的 SQL Pivot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有多个值的 SQL Pivot
基础教程推荐
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
