SQL Pivot 问题 - 多个聚合?

发布于 2024-09-29 12:28:28 字数 948 浏览 0 评论 0原文

我有以下数据返回购买一个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帝王念 2024-10-06 12:28:28

在对事故现场重新进行数据透视之前,您需要取消数据透视 - 如下所示:

select * 
from Example
unpivot 
(
numbers 
for type in (x,y,z)
) as p
pivot 
(
Max(numbers)
for site in ([A],[B],[C])
) as q

You need to UNPIVOT your data, before rePIVOTing it about the accident site - like so:

select * 
from Example
unpivot 
(
numbers 
for type in (x,y,z)
) as p
pivot 
(
Max(numbers)
for site in ([A],[B],[C])
) as q
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文