简体   繁体   English

SQL 将列拆分为新列

[英]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我想将两列“AvgExpected”和“AvgNow”合并到一个 Avg 列

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在 Name 列中,我想知道 AVG 是什么,因为我们合并了两个 AVG 列,所以名称将是“Name1”,并与之前的“AvgExpected”或“AvgNow”列连接,并提供准确的数据

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 :您可以使用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:然后通过删除那些没有 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.您可以向表中添加一个约束,以防止在此迁移后NULL中出现AvgType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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