sql - 将 YYYYMM 字符串转换为第 1 天的日期 YYYY-MM-DD
问题描述
我从表格中有这个列Startmonth,它是这样的日期:YYYYMM,所以201801,201707等。
我希望在我的视图中创建此列,但将其转换为日期,例如YYYY-MM-DD,其中日期为每月的第一天,因此 **201801 > 2018-01-01 和 201707 > 2017- 07-01。**
我不断收到错误:
从字符串转换日期和/或时间时转换失败。
有人可以帮我吗?
我试过这个:
select convert (DATE, concat (s.StartMonth,'01'), 102) as SubscriptionStart
from incident i
left join imcustomerid cid on i.accountid = cid.accountid
left join billing_subscription s on cid.imcustomerid = s.idcustomer
left join billing_subscriptiontype st on s.idsubscriptiontype = st.id
解决方案
尝试使用
select convert (DATE, concat (s.StartMonth,'01'), 112) as SubscriptionStart
或者
select cast(concat (s.StartMonth,'01') as date) as SubscriptionStart
TRY_CONVERT
正如@Larnu 所说,我认为在这里使用更好:
select try_convert(date, s.StartMonth+'01', 112) as SubscriptionStart
而+
不是CONCAT
正确转换 NULL 值。
推荐阅读
- python - 通过 pip 安装 Flask
- php - 如何在android中使用php添加多个标记
- javascript - 可点击的“显示隐藏”文本或剧透的最小(最短)HTML
- hadoop - 从一个集群到另一个集群的 HDFS 数据传输不适用于 distcp
- ios - 通过 Segue 将数据传递到另一个 Storyboard 中的 UITabBarController 推送到导航堆栈
- python - 监督文本相似度
- python - 修复 Python 中的 ValueError 以计算投资组合标准差
- xamarin - 触发滚动后,带有自定义渲染器的 Xamarin.Forms ListView 选择多行
- facebook - 获取用户的 Facebook 粉丝页面信息,例如点赞数和关注者
- sql-server - SSRS 报告 - 导出到 Excel 日期时间过滤