【问题标题】:How to SELECT Date and TIme from Date time column using ON Clause如何使用 ON 子句从日期时间列中选择日期和时间
【发布时间】:2019-03-06 07:05:30
【问题描述】:

我有一个连接查询

SELECT  vs.Id as 'VitalId', ms.PatientId as 'PatientId',  ms.CustomerId  as 'CustomerId', ms.CreatedUtc
from A1 a
join B1 b
    on a.CreatedUtc = b.concat(concat(convert(date,S.CreatedUtc),':'),
                               datepart(hour,S.CreatedUtc))

实际上我想将 a.CreatedUtc 映射到 b 表的日期和时间(即:- B2)。 这个查询有效吗?因为当我运行此查询时,没有插入任何记录。

谁能告诉我如何使用 ON 子句从日期时间列中仅获取日期和时间?

【问题讨论】:

  • 请显示两个表的示例数据和表结构。
  • 无论架构和实际问题是什么,都有没有理由在日期上使用字符串操作。如果CreatedUtc 中的任何一个是文本,那么真正的问题是错误的数据类型,而不是连接表达式。在这两种情况中,不可能在这些字段上使用索引,从而导致查询非常缓慢

标签: sql sql-server sql-server-2008 sql-server-2005


【解决方案1】:

这是你想要的吗?

select vs.Id as VitalId, ms.PatientId as PatientId,  
       ms.CustomerId  as CustomerId, ms.CreatedUtc
from A1 a join
     B1 b
     on convert(date, a.CreatedUtc) = convert(date, S.CreatedUtc) and
        datepart(hour, a.CreatedUtc) = datepart(hour, S.CreatedUtc);

【讨论】:

  • 不完全是..我不想要datepart..是否可以在单行中实现日期和小时。?
猜你喜欢
  • 2010-12-17
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
相关资源
最近更新 更多