我正在处理一个视图,并有下表,我试图修改它(sql服务器)
表x
ID Value End_time
1 10 2019-12-06T07:00:00+0000
2 15 2020-01-07T07:00:00+0000
2 20 2020-01-31T07:00:00+0000
3 25 2020-02-02T07:00:00+0000
3 30 2020-02-28T07:00:00+0000
4 35 2020-03-05T07:00:00+0000
4 40 2020-03-31T07:00:00+0000
[end_time]必须从varchar转换为date,并在月份和年份中进一步拆分,然后我必须根据年度和月份的数据选择最大日期和组。
所以我提出以下问题
SELECT [ID], [Value], CONVERT(date, LEFT([End_time], LEN([End_time]) - 14)) AS [date],
-- convert to date
MONTH(CONVERT(date, LEFT([End_time], LEN([End_time]) - 14))) AS Month_Name, --get month
YEAR(CONVERT(date, LEFT([End_time], LEN([End_time]) - 14))) AS Year_Name --get year
FROM X AS Table
INNER JOIN --join on itself
(SELECT MAX([date]) AS MaxDate, MONTH([date]) AS Month_Name, YEAR(date) AS Year_Name
FROM X
GROUP BY MONTH([date]), YEAR([date])) AS D ON D.MaxDate = CONVERT(date,
LEFT([End_time], LEN([End_time]) - 14))
但我得到一个错误,没有日期这样的列。我试着这样加入:
INNER JOIN --join on itself
(SELECT MAX(CONVERT(date, LEFT([End_time], LEN([End_time]) - 14))) AS MaxDate,
MONTH([date]) AS Month_Name, YEAR(date) AS Year_Name
FROM X
GROUP BY MONTH([date]), YEAR([date])) AS D ON D.MaxDate = CONVERT(date,
LEFT([End_time], LEN([End_time]) - 14))
但是我得到了一个错误,多部分标识符“x.end\u time”无法绑定。
所以我的理想结果是
ID Value Month_Name Year_Name
1 10 12 2019
2 35 01 2020
3 55 02 2020
4 75 03 2020
2条答案
按热度按时间j2qf4p5b1#
我只想用:
尽管将日期/时间值存储为字符串是一个错误的表示选择,但您至少为该字符串选择了一种非常好的格式。您只需按字符串排序即可获得最新或最旧的行。
icnyk63a2#