sql将小时转换为日期时间,而不在单位数字小时上删除前导零
CAST(DATEPART(hh, timestamp) AS varchar(2)) + ':00' AS Hour
这将使我从时间戳字段中获取小时,但在 0-9 小时的情况下,它不会填充前导零,因此当我按小时降序排序时,它无法正确排序。
不知道这里出了什么问题。我指定了 2 个字符的 varchar 以便为前导零留出额外的空间。希望有一种方法可以解决这个问题,而无需通过一个函数来填充我的字段,该函数将为我填充前导零。
CAST(DATEPART(hh, timestamp) AS varchar(2)) + ':00' AS Hour
This will get me the hour out of a timestamp field but in the case of the hours 0-9 it does not pad a leading zero and therefore when I sort by hour descending it does not sort correctly.
Not sure what is wrong here. I specify a 2 char varchar to allow extra room for the leading zero. Hopefully there is a way to fix this without passing my field through a function that will pad the leading zero for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不想用 0 填充?好吧,你可以用类似丑陋的方式来做,而不会造成填充混乱:
显然用你的列名替换
GETDATE()
。我希望这不是真正的时间戳,因为这是一个保留字 - 对于与日期或时间无关的数据类型,遗憾的是。如果您不喜欢这些解决方案中的任何一个,那么只需从 SQL Server 选择数据并让您的客户端应用程序处理格式/表示细节。当然,使用 C# 的
format()
函数可以很容易地做到这一点。Don't want to pad with 0s? OK, you can do it a similarly ugly way without the padding mess:
Obviously replace
GETDATE()
with your column name. Which I hope isn't reallytimestamp
because this is a reserved word - for a data type that has nothing to do with date or time, sadly.If you don't like either of those solutions, then just select the data from SQL Server and let your client application handle formatting/presentation details. Surely this is easy to do with C#'s
format()
function, for example.可以使用TIME类型,默认是24小时;
You can use the TIME type which is 24 hours by default;
假设时间戳是表中的一列
替代
编辑:
经过一番测试后我得出的结论是这是最快的方法(几乎是亚伦解决方案的性能和语法)
Assuming timestamp is a column in your table
Alternative
Edit:
After testing a bit i came to the conclusion that this is the fastest way (almost the performance and syntax as Aaron's solution)