SQL Server Convert row into columns with duplicates

lztngnrs  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(188)

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.

3htmauhk

3htmauhk1#

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

相关问题