如何在sql server 2005/8中没有聚合函数的情况下进行列到行?
例如,我需要从
更改为
.
我知道 PIVOT 就是用于此目的,但它需要一个聚合函数;对于我的情况,我不需要聚合,只需要列到行。
您可以使用以下示例数据:
CREATE TABLE[StudentScores]
(
[UserName] NVARCHAR(20),
[Subject] NVARCHAR(30),
[Score]FLOAT,
)
GO
INSERT INTO[StudentScores]SELECT'Nick','Chinese',80
INSERT INTO[StudentScores]SELECT'Nick','Maths',90
INSERT INTO[StudentScores]SELECT'Nick','English',70
INSERT INTO[StudentScores]SELECT'Nick','Biology',85
INSERT INTO[StudentScores]SELECT'Kent','Chinese',80
INSERT INTO[StudentScores]SELECT'Kent','Maths',90
INSERT INTO[StudentScores]SELECT'Kent','English',70
INSERT INTO[StudentScores]SELECT'Kent','Biology',85
For example, I need to change from
to
.
I know PIVOT is for that, but it requires an aggregate function; and for my case, I donot need to aggregate only need column to row.
You can use the following sample data:
CREATE TABLE[StudentScores]
(
[UserName] NVARCHAR(20),
[Subject] NVARCHAR(30),
[Score]FLOAT,
)
GO
INSERT INTO[StudentScores]SELECT'Nick','Chinese',80
INSERT INTO[StudentScores]SELECT'Nick','Maths',90
INSERT INTO[StudentScores]SELECT'Nick','English',70
INSERT INTO[StudentScores]SELECT'Nick','Biology',85
INSERT INTO[StudentScores]SELECT'Kent','Chinese',80
INSERT INTO[StudentScores]SELECT'Kent','Maths',90
INSERT INTO[StudentScores]SELECT'Kent','English',70
INSERT INTO[StudentScores]SELECT'Kent','Biology',85
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果每个主题只有一条记录,您可以使用 MIN 或 MAX。
If there is going to be one record per subject you can use MIN or MAX.
我无法从你原来的问题中完全看出你想改变哪个领域——科目还是分数。但是,您可以使用
PIVOT< /code>
来执行此操作。如果您知道要从行更改为列的列数,则可以使用静态数据透视(类似于其他答案)。如果您不知道要转换的列数,则可以使用动态数据透视:
请参阅 SQL Fiddle在演示中
,如果用户每个科目有多个分数,我会使用
AVG()
聚合。I cannot quite tell from your original question which field you want to transform - subject or score. However, you can use a
PIVOT
to perform this. If you know the number of columns you want to change from rows to columns, then you can use a static pivot (similar to the other answer). If you do not know the number of columns to transform, then you can use a dynamic pivot:See SQL Fiddle with Demo
I used the
AVG()
aggregate in the event a user has more than one score per subject.11g 中新的 PIVOT 运算符可以帮助您实现所需的输出。例如检查这个
http://querydb.blogspot.in /2014/05/get-data-in-rows-and-aggregates-into.html
The new PIVOT operator in 11g can help you achieve desired output. Check this for example
http://querydb.blogspot.in/2014/05/get-data-in-rows-and-aggregates-into.html