使用SQL中另一列的值替换”Value”。

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

Replace Value with value from another Column in SQL

问题

在SQL中,我有两列,ReportedDateDATETIME)和ReportedTimechar(5)),其中ReportedDate列始终显示时间为0,例如'2022-10-04 00:00:00.000'。

我需要将同一行中的ReportedDateReportedTime值合并到一个新列中显示。

结果需要是DATETIME数据类型。

例如:

  • ReportedDate: '2022-10-04 00:00:00.000'

  • ReportedTime: '10:17'

  • 期望的最终结果: '2022-10-04 10:17:00.000'

当我尝试这样做时:

SELECT 
    CONVERT(DATETIME, REPLACE(ReportedDate, '00:00:00', CONVERT(time, ReportedTime))) AS StartTime
FROM EventDate

我的最终结果在新的StartTime列中没有对ReportedDate进行任何更改,我怀疑这是因为REPLACE函数无法读取ReportedTime的值,因为它没有加上引号。

英文:

In SQL I have 2 columns, ReportedDate (DATETIME) and ReportedTime (char(5)) with the ReportedDate column always showing 0s for the times, ex. '2022-10-04 00:00:00.000'.

I need to combine the ReportedDate and ReportedTime values from the same row to be displayed in a new column.

The result needs to be of DATETIME data type.

For example:

  • ReportedDate: '2022-10-04 00:00:00.000'

  • ReportedTime: '10:17'

  • Desired end result: '2022-10-04 10:17:00.000'

When I tried this:

SELECT 
    CONVERT(DATETIME, REPLACE(ReportedDate, '00:00:00', CONVERT(time, ReportedTime))) AS StartTime
FROM EventDate

My end result returned ReportedDate with no changes made to it in the new StartTime column, which I suspect is happening because the REPLACE function isn't able to read the ReportedTime value because its not in quotes.

答案1

得分: 1

您可以使用CONCAT来连接这两列

更新
根据编辑,问题更加清晰。

> ReportedDate格式:'2022-10-04 00:00:00.000'
>
> ReportedTime格式:'10:17'
>
> 期望的最终结果:'2022-10-04 10:17:00.000'

可以按照以下方式实现:

select
    CONVERT(DATETIME, CONCAT(CONVERT(VARCHAR, ReportedDate, 23), ' ', ReportedTime)) AS StartTime
from EventDate

这里有更多参考资料:
如何在SQL Server中获取不同的日期格式

英文:

You can use CONCAT to concatenate these two columns

Update:
Based on edit the question is more clear.

> ReportedDate format : '2022-10-04 00:00:00.000'
>
> ReportedTime format: '10:17'
>
> Desired end result: '2022-10-04 10:17:00.000'

This can be achieved as follows :

select
    CONVERT(DATETIME, CONCAT(CONVERT(VARCHAR, ReportedDate, 23), ' ', ReportedTime)) AS StartTime
from EventDate

Here is a more reference for :
How to get different date formats in SQL Server

huangapple
  • 本文由 发表于 2023年3月4日 00:33:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629653.html
匿名

发表评论

匿名网友

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

确定