gpt4 book ai didi

SQL Server 非常乐意添加日期和月份

转载 作者:行者123 更新时间:2023-12-01 21:17:38 26 4
gpt4 key购买 nike

我从这个查询开始。

select 
count(datepart(day, SomeTime)) as NumberOf,
datepart(day, SomeTime) as DaySansMonth
from PMStationTightenings
group by datepart(day, SomeTime)

它做了应该做的事情,但不方便地呈现。因此,我对其进行了改造,使其也包含月份。

select 
count(datepart(day, SomeTime)) as NumberOf,
datepart(month, SomeTime) + ' ' + datepart(day, SomeTime) as DayAndMonth
from PMStationTightenings
group by datepart(month, SomeTime) + ' ' + datepart(day, SomeTime)

计算机试图变得聪明,无论如何都会添加数字,所以而不是例如8 5 我得到13。不够完美。为什么? (当然,我知道它将两个数字解释为整数,但为什么?之间显然有一个空格...)

无论如何,我会继续让它旅行,但放入它无法添加的东西。现在我心里想“哈!明白了!”。你相信吗?这台愚蠢的计算机向我咆哮,扔出这些令人讨厌的红色东西,就像犯了一个错误一样。难以置信!好神经啊! :)

select 
count(datepart(day, SomeTime)) as NumberOf,
datepart(month, SomeTime) + '|' + datepart(day, SomeTime) as DayAndMonth
from PMStationTightenings
group by datepart(month, SomeTime) + '|' + datepart(day, SomeTime)

我怎样才能用 b!"#¤ 来制作计算机并强制它从数据库中提供月/日组合?

最佳答案

Jim already explained how you can fix this ,这是原因

引用自SQL Server's Data Type Precedence :

When an operator combines two expressions of different data types, the rules for data type precedence specify that the data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned.

您正在组合 INT(DATEPART 的返回值)和 (N)VARCHAR,但 INT 有优先级高于 (N)VARCHAR),因此 SQL Server 尝试将整个事物视为 INT

一般来说,如果您在一个表达式中处理不同的数据类型,则应尽量避免隐式转换并尽可能显式转换。因此,只需将您的值转换/转换为合适的类型即可。

编辑:由于 Anthony Grist,更正了有关所涉及数据类型的部分

关于SQL Server 非常乐意添加日期和月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com