SQL查询以帮助转置数据

huangapple go评论67阅读模式
英文:

SQL query to help transpose data

问题

我正在尝试编写一个SQL查询,将数据转置到一个新列中,我已经进行了一些与pivot相关的研究,但我不确定我是否正确理解如何使用它,或者也许我不应该使用它,查询可以用不同的格式编写。感谢任何帮助。谢谢。

SQL查询以帮助转置数据

英文:

I'm trying to write a SQL query to transpose the data into a new column, I've done some research with pivot, but I'm not sure I understand how to use it properly, or maybe I shouldn't be using that and the query can be written in a different format. Any help is appreciated. Thanks

SQL查询以帮助转置数据

答案1

得分: 1

这可以使用条件聚合来完成:

select serial,
       MAX(case when externalID <> 47 then MyValues end) as MyValues,
       MAX(case when externalID = 47 then MyValues end) as NuwColumn
from mytable
group by serial

这段代码适用于主要的数据库,如mysqlpostgresql...

英文:

This can be done using the conditional aggregation :

select serial,
       MAX(case when externalID <> 47 then MyValues end) as MyValues,
       MAX(case when externalID = 47 then MyValues end) as NuwColumn
from mytable
group by serial

This code works on major databases such as mysql and postgresql...

答案2

得分: 0

作为@SelVazi版本的替代(因为我不喜欢聚合函数):

SELECT t1.[Serial], t1.[MyValues], t2.[MyValues] AS [NewColumn] 
FROM [Table1] t1
	INNER JOIN [Table1] t2
	ON t1.Serial = t2.Serial 
	WHERE t1.ExternalID = 43 AND t2.ExternalID = 47

(注意:这是MS SQL Server版本)

英文:

As an alternative to @SelVazi version (because I hate aggregating functions):

SELECT t1.[Serial], t1.[MyValues], t2.[MyValues] AS [NewColumn] 
FROM [Table1] t1
	INNER JOIN [Table1] t2
	ON t1.Serial = t2.Serial 
	WHERE t1.ExternalID = 43 AND t2.ExternalID = 47

(NOTE: this is an MS SQL Server version)

huangapple
  • 本文由 发表于 2023年5月10日 20:18:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218335.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定