SQL Pivot 问题 - 多个聚合?
我有以下数据返回购买一个简单的 SQL 查询。站点数量可能会改变,但 X、Y、Z 是固定的(它们是不同类型的事故,存储的数据代表发生次数)
| Site | X | Y | Z |
--------------------
A 1 2 3
B 4 5 6
C 7 8 9
我需要将其转换为以下格式
| A | B | C |
--------------
1 4 7
2 5 8
3 6 9
到目前为止我已经有了
select *
from Example
pivot
(
Max(X)
for site in ([A],[B],[C])
) as p
但我认为我需要多个聚合(对于 X、Y 和 Z)。
这是一个创建基础数据的快速脚本,
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Example](
[Site] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[X] [int] NOT NULL,
[Y] [int] NOT NULL,
[Z] [int] NOT NULL
) ON [PRIMARY]
insert into Example(Site, X,Y,Z) Values ('A',1,2,3)
insert into Example(Site, X,Y,Z) Values ('B',4,5,6)
insert into Example(Site, X,Y,Z) Values ('C',7,8,9)
非常欢迎任何帮助,因为我陷入困境!
标记
I have the following data returned buy a simple SQL query. The Number of sites could change, but X,Y,Z are fixed (they are different types of accidents, and the data stored represents the number of occurances)
| Site | X | Y | Z |
--------------------
A 1 2 3
B 4 5 6
C 7 8 9
I need to get it to the following format
| A | B | C |
--------------
1 4 7
2 5 8
3 6 9
I have this so far
select *
from Example
pivot
(
Max(X)
for site in ([A],[B],[C])
) as p
But I think I need multiple aggregates (for X, Y and Z).
Here is a quick script to create the base data
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Example](
[Site] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[X] [int] NOT NULL,
[Y] [int] NOT NULL,
[Z] [int] NOT NULL
) ON [PRIMARY]
insert into Example(Site, X,Y,Z) Values ('A',1,2,3)
insert into Example(Site, X,Y,Z) Values ('B',4,5,6)
insert into Example(Site, X,Y,Z) Values ('C',7,8,9)
Any help really welcome as I am stuck!
Mark
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在对事故现场重新进行数据透视之前,您需要取消数据透视 - 如下所示:
You need to UNPIVOT your data, before rePIVOTing it about the accident site - like so: