英文:
Replace Value with value from another Column in SQL
问题
在SQL中,我有两列,ReportedDate
(DATETIME
)和ReportedTime
(char(5)
),其中ReportedDate
列始终显示时间为0,例如'2022-10-04 00:00:00.000'。
我需要将同一行中的ReportedDate
和ReportedTime
值合并到一个新列中显示。
结果需要是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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论