SQL 当前月/年问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6685300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Current month/ year question
提问by GabrielVa
So I have a table that has the month and year broken down, for example field called Month has the number 7 in it (this month) and the Year field has 2011. Theres also additional months years, etc. How can I query this to show just the current year, month?
所以我有一个表,其中有月份和年份分解,例如名为 Month 的字段中有数字 7(这个月),Year 字段有 2011 年。还有额外的月份年份等。我如何查询这个只显示当前的年月?
回答by Christian Specht
In SQL Server you can use YEAR
, MONTH
and DAY
instead of DATEPART
.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)
在 SQL Server 中,您可以使用YEAR
,MONTH
和DAY
代替DATEPART
。
(至少在 SQL Server 2005/2008 中,我不确定 SQL Server 2000 及更早版本)
I prefer using these "short forms" because to me, YEAR(getdate())
is shorter to type and better to read than DATEPART(yyyy, getdate())
.
我更喜欢使用这些“简短形式”,因为对我来说,YEAR(getdate())
它比DATEPART(yyyy, getdate())
.
So you could also query your table like this:
所以你也可以像这样查询你的表:
select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
回答by Abe Miessler
This should work for SQL Server:
这应该适用于 SQL Server:
SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())
回答by Alan Cole
This should work in MySql
这应该在 MySql 中工作
SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);
回答by FrustratedWithFormsDesigner
How about:
怎么样:
Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
st.year = to_char(sysdate,'YYYY');
should work in Oracle. What database are you using? I ask because not all databases have the same date functions.
应该在 Oracle 中工作。你用的是什么数据库?我问是因为并非所有数据库都具有相同的日期函数。
回答by JIYAUL MUSTAPHA
DECLARE @CMonth int=null
DECLARE @lCYear int=null
SET @lCYear=(SELECT DATEPART(YEAR,GETDATE()))
SET @CMonth=(SELECT DATEPART(MONTH,GETDATE()))
回答by Mubin .N
select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());
select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());
Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.
注意:(month_year) 表示包含日期格式的列。我认为这将解决您的问题。如果该查询不起作用,请告诉我。