如何获得此结果?

62lalag4  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(266)

编写select语句,从db1.myguitarshop.products表中返回以下列:
a) dateadded列
b) 使用cast函数返回仅包含日期(年、月和日)的dateadded列的列
c) 使用cast函数返回dateadded列的列,该列仅返回其完整时间(小时、分钟、秒和毫秒)
d) 一个使用cast函数返回dateadded列的列,其中只包含月份和日期
这是我目前的情况:

SELECT
    DateAdded,
    CAST(DateAdded AS decimal(10, 1)) AS AddedDate,
    CAST(DateAdded AS decimal(10)) AS AddedTime,
    CAST(DateAdded AS int) AS AddedChar7
FROM MyGuitarShop.Products;
41ik7eoe

41ik7eoe1#

CAST 转换为 DATE 以及 TIME 这很简单。但第三项更为棘手,涉及两个独立的项目 CASTS ,然后是字符串串联。
像这样的东西应该起作用:
注意,我在一个变量中( @dt )只是为了更简单地演示这个概念。

DECLARE @dt DATETIME = GETDATE()
SELECT      @dt
        ,   CAST(@dt AS Date) AS AddedDate
        ,   CAST(@dt AS Time) AS AddedTime
        ,   CAST(MONTH(@dt) AS VARCHAR(4)) + CAST(DAY(@dt) AS VARCHAR(4)) AS AddedChar

这是一把小提琴

apeeds0o

apeeds0o2#

另一种选择是使用 CONVERT 将日期转换为文本。它的优点是允许您为结果选择特定的格式。。。
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15

SELECT
    DateAdded,
    CONVERT(varchar(128), DateAdded, 111) AS AddedDate,
    CONVERT(varchar(128), DateAdded, 14) AS AddedTime,
    CAST(DATEPART(MONTH, DateAdded) as varchar(2)) + '/' + CAST(DATEPART(DAY, DateAdded) as varchar(2)) AddedChar7
FROM (VALUES
        (GETDATE())
    )Products(DateAdded)
wwodge7n

wwodge7n3#

SELECT  DateAdded
        ,Cast(DateAdded as date) Cast_YMD --Default for date is YMD
        ,Cast(DateAdded as time) Cast_HMSM -- Default for time is HMSM
        ,CAST(DateAdded as char(6)) Cast_MMDD --The 6 characters in the date field are month(as 3 char name Jan,Feb...) and day(as 2 digit)   
FROM Products

相关问题