将行转换为带有重复的列

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

Convert row into columns with duplicates

问题

我需要将SQL Server中的行转换为列,同时包括值和日期。

这是我的示例数据集:

将行转换为带有重复的列

我希望显示如下:

将行转换为带有重复的列

我尝试了case when条件,并获得了以下结果。但我不想创建更多的重复项。

代码:

SELECT
    id,
    CASE WHEN name = 'BP' THEN value ELSE NULL END AS BP_value,
    CASE WHEN name = 'BP' THEN date ELSE NULL END AS BP_date,
    CASE WHEN name = 'Pulse' THEN value ELSE NULL END AS Pulse_value,
    CASE WHEN name = 'Pulse' THEN date ELSE NULL END AS Pulse_date
FROM 
    table_name

结果:

将行转换为带有重复的列

请帮助我解决这个问题。

英文:

I need to convert SQL Server rows into columns along with it value and dates.

Here is my sample dataset:

将行转换为带有重复的列

I required it to be shown like this:

将行转换为带有重复的列

I tried case when conditions and I got this results. But I don't want to make more duplicates.

Code:

SELECT
	id,
	CASE WHEN name = 'BP' THEN value ELSE NULL AS END AS BP_value,
	CASE WHEN name = 'BP' THEN date ELSE NULL AS END AS BP_date,
	CASE WHEN name = 'Pulse' THEN value ELSE NULL AS END AS Pulse_value,
	CASE WHEN name = 'Pulse' THEN date ELSE NULL AS END AS Pulse_date
FROM 
	table_name

Result:

将行转换为带有重复的列

Please help me with this.

答案1

得分: 2

使用聚合功能:

SELECT
    id,
    date,
    MAX(CASE WHEN name = 'BP' THEN value ELSE NULL END) AS BP_value,
    MAX(CASE WHEN name = 'BP' THEN date ELSE NULL END) AS BP_date,
    MAX(CASE WHEN name = 'Pulse' THEN value ELSE NULL END) AS Pulse_value,
    MAX(CASE WHEN name = 'Pulse' THEN date ELSE NULL END) AS Pulse_date
FROM 
    table_name
GROUP BY id, date
英文:

Use aggregation:

SELECT
    id,
    date,
    MAX(case when name = 'BP' THEN value ELSE NULL as end) as BP_value,
    MAX(case when name = 'BP' THEN date ELSE NULL as end) as BP_date,
    MAX(case when name = 'Pulse' THEN value ELSE NULL as end) as Pulse_value,
    MAX(case when name = 'Pulse' THEN date ELSE NULL as end) as Pulse_date
FROM 
    table_name
GROUP BY id, date

huangapple
  • 本文由 发表于 2023年3月8日 14:26:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75669966.html
匿名

发表评论

匿名网友

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

确定