【问题标题】:Populate value for new column based on other columns根据其他列填充新列的值
【发布时间】:2021-01-03 15:33:04
【问题描述】:

我在 SQL Server 2016 中有一个表,它有 3 列,(Id,Month,Year) 现在我想向现有表添加一个新列,其值应根据月和年列的值填充对于现有记录,甚至对于以后插入的新记录。

预期输出:

Id  Month       Year      Del_Range
------------------------------------
1   January     2020      2020-01-01
2   February    2020      2020-02-01
3   March       2020      2020-03-01

查询:

CREATE TABLE tempdb..#test
(
    Id int,
    [Month] varchar(50),
    [Year] int,
)
GO

INSERT INTO tempdb..#test (Id, [Month], [Year])
VALUES (1, 'January', 2020), 
       (2, 'February', 2020), 
       (3, 'March', '2020')
GO

SELECT * FROM tempdb..#test
GO

ALTER TABLE tempdb..#test
    ADD Del_Range DATE
-- Need to add logic to populate value for this column based on value from Month and Year to get expected output

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    试试下面的查询

    alter table #test add Del_Range as convert(date, concat([year], [month], id)) 
    
    insert into #test(id, month, year)
    select 4, 'april', 2020
    union 
    select 4, 'May', 2020
    

    【讨论】:

      【解决方案2】:

      你可以试试这个命令。

      alter table #test add Del_Range as cast(cast(Year as varchar(4)) + Month + '01' as date)--for first day for a month
      

      【讨论】:

        猜你喜欢
        • 2020-02-04
        • 2021-06-19
        • 1970-01-01
        • 2021-12-10
        • 2019-06-06
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        相关资源
        最近更新 更多