简体   繁体   中英

SQL split column to new columns

Hey I am working on a project and I want to split the data from two columns to a new one

Current Values:

EndTime                AvgExpected    AvgNow    Name
2022-12-04 07:17:00.000 83.031000   83.626571   Name1
2022-12-04 07:32:00.000 83.034428   83.546571   Name1
2022-12-04 07:47:00.000 83.021571   83.555142   Name1
2022-12-04 08:02:00.000 83.033285   83.533285   Name1
2022-12-04 08:17:00.000 83.038285   83.346571   Name1
2022-12-04 08:32:00.000 83.026857   83.346571   Name1
2022-12-04 08:47:00.000 83.037285   83.351714   Name1
2022-12-04 09:02:00.000 83.057000   83.445142   Name1

I want to merge the two columns "AvgExpected" and "AvgNow" to one Avg column

In the Name column I want to know what AVG is that because we merged the two AVG columns so the name will be "Name1" concated with the previous "AvgExpected" or "AvgNow" column with the exact data

Example of how I would like the table to look like:

    EndTime                     Avg         Name
    2022-12-04 07:17:00.000 83.626571   Name1 AvgNow
    2022-12-04 07:32:00.000 83.546571   Name1 AvgNow    
    2022-12-04 07:47:00.000 83.555142   Name1 AvgNow    
    2022-12-04 08:02:00.000 83.533285   Name1 AvgNow    
    2022-12-04 08:17:00.000 83.038285   Name1 AvgExpected     
    2022-12-04 08:32:00.000 83.026857   Name1 AvgExpected     
    2022-12-04 08:47:00.000 83.037285   Name1 AvgExpected     
    2022-12-04 09:02:00.000 83.057000   Name1 AvgExpected     

I hope that my examples are clear

this is the current query

SELECT EndTime,avg(E_AVG) as AvgExpected,avg(Avg_Now)AvgNow,Name
FROM table1 
where Name='Name1' and (EndTime between '2022-12-04 07:17' and '2022-12-04 15:17')
group by EndTime, Name
order by EndTime

I've made a small adjustment to the requirement as I think you'll want the "type of average" to be a new column.

You can generate the new records using a UNION :

INSERT INTO table1 (EndTime, Avg, Name, AvgType)
SELECT
  EndTime,
  AvgExpected AS Avg,
  Name,
  'AvgExpected' AS AvgType
FROM
  table1
UNION ALL
SELECT
  EndTime,
  AvgNow AS Avg,
  Name,
  'AvgNow' AS AvgType
FROM
  table1

And then remove the old records by removing those with no AvgType:

DELETE FROM table1
WHERE AvgType IS NULL

You could add a constraint to the table to prevent NULL in the AvgType after this migration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM