查询 YYYYMMDD 格式的列以仅显示当前月份值?

问题描述 投票:0回答:1

我有一个如下表1,第一列名为“Calendar_Day”,格式为YYYYMMDD

日历_日 植物 股票
20240316 ABC 100
20240511 防御 850
20240508 GHI 520
20240105 JKL 222

我只需要当前月份的行(例如,现在是2024年5月,所以它只需要显示202405XX,但下个月,它应该自动仅显示202406XX)

日历_日 植物 股票
20240511 防御 850
20240508 GHI 520

我应该如何用 SQL 编写查询?

select *
from table1
where ??????

谢谢!

我尝试使用 if、concate 但都导致错误。

sql sql-server
1个回答
0
投票

这将是一个简单的查询,用于检查当前月份和年份并从表 1 中获取数据。

-- Assuming the current year and month as parts of the date
DECLARE @currentYearMonth CHAR(6) = CONVERT(CHAR(6), GETDATE(), 112)  -- YYYYMM format

Select @currentYearMonth as currentYearMonth
/*
currentYearMonth
----------------
202405
*/

SELECT *
FROM table1
WHERE LEFT(Calendar_Day, 6) = @currentYearMonth;
/*
Calendar_Day Plant      Stocks
------------ ---------- -----------
20240511     DEF        850
20240508     GHI        520
*/
© www.soinside.com 2019 - 2024. All rights reserved.