특정 월의 모든 레코드를 찾는 WHERE 절
저장 프로 시저에 월과 연도를 부여하고 그 달에 발생한 모든 일을 반환하도록하고 싶습니다. 어떤 달에는 일 수가 다르기 때문에 비교할 수 없기 때문에 어떻게해야합니까?
이를 수행하는 가장 좋은 방법은 무엇입니까? 연도와 월을 기준으로 비교를 요청할 수 있습니까?
감사.
나는 당신이 찾고있는 기능이라고 생각합니다 MONTH(date)
. 'YEAR' 도 사용하고 싶을 것입니다 .
다음 things
과 같은 이름의 테이블이 있다고 가정 해 보겠습니다 .
id happend_at
-- ----------------
1 2009-01-01 12:08
2 2009-02-01 12:00
3 2009-01-12 09:40
4 2009-01-29 17:55
happened_at
2009/01 월 (2009 년 1 월) 동안 a가있는 모든 레코드를 찾기 위해 실행하려고한다고 가정 해 보겠습니다 . SQL 쿼리는 다음과 같습니다.
SELECT id FROM things
WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009
다음을 반환합니다.
id
---
1
3
4
대부분의 응답에서 제안 된대로 MONTH 및 YEAR 함수를 사용하면 SQL Server가 날짜 열에있을 수있는 인덱스를 사용할 수 없다는 단점이 있습니다. 이것은 큰 테이블에서 성능을 저하시킬 수 있습니다.
관심있는 달의 첫 번째 날을 나타내는 저장 프로 시저에 DATETIME 값 (예 : @StartDate)을 전달하는 경향이 있습니다.
그런 다음 사용할 수 있습니다.
SELECT ... FROM ...
WHERE DateColumn >= @StartDate
AND DateColumn < DATEADD(month, 1, @StartDate)
저장 프로 시저에 별도의 매개 변수로 월과 연도를 전달해야하는 경우 CAST 및 CONVERT를 사용하여 월의 첫 번째 날을 나타내는 DATETIME을 생성 한 다음 위와 같이 진행할 수 있습니다. 이렇게하면 정수 년, 월, 일 값에서 DATETIME을 생성하는 함수를 작성하는 것이 좋습니다. 예를 들어 SQL Server 블로그 의 다음과 같습니다 .
create function Date(@Year int, @Month int, @Day int)
returns datetime
as
begin
return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
end
go
그러면 쿼리는 다음과 같이됩니다.
SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
더 많은 팁이 매우 간단합니다. to_char 함수를 사용할 수도 있습니다 .
한 달 동안 :
to_char (happened_at, 'MM') = 01
년 동안 :
to_char (happened_at, 'YYYY') = 2009
하루 동안 :
to_char (happened_at, 'DD') = 01
to_char 함수는 특정 데이터베이스가 아닌 SQL 언어로 지원됩니다.
더 많은 사람을 돕길 바랍니다 ...
복근!
SQL Server를 사용하는 경우 DATEPART를 살펴보십시오.
http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx
DATEPART (mm, [보고있는 날짜])
그런 다음 일반 정수 논리를 사용할 수 있습니다. 연도와 동일하며 mm 대신 yy를 사용하십시오.
MONTH 및 YEAR 함수의 대안으로 일반 WHERE 절도 작동합니다.
select *
from yourtable
where '2009-01-01' <= datecolumn and datecolumn < '2009-02-01'
I find it easier to pass a value as a temporal data type (e.g. DATETIME
) then use temporal functionality, specifically DATEADD
and DATEPART
, to find the start and end dates for the period, in this case the month e.g. this finds the start date and end date pair for the current month, just substitute CURRENT_TIMESTAMP
for you parameter of of type DATETIME
(note the 1990-01-01 value is entirely arbitrary):
SELECT DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-01T00:00:00.000'),
DATEADD(M,
DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP),
'1990-01-31T23:59:59.997')
Can I just ask to compare based on the year and month?
You can. Here's a simple example using the AdventureWorks sample database...
DECLARE @Year INT
DECLARE @Month INT
SET @Year = 2002
SET @Month = 6
SELECT
[pch].*
FROM
[Production].[ProductCostHistory] pch
WHERE
YEAR([pch].[ModifiedDate]) = @Year
AND MONTH([pch].[ModifiedDate]) = @Month
Something like this should do it:
select * from yourtable where datepart(month,field) = @month and datepart(year,field) = @year
Alternatively you could split month and year out into their own columns when creating the record and then select against them.
Iain
One way would be to create a variable that represents the first of the month (ie 5/1/2009), either pass it into the proc or build it (concatenate month/1/year). Then use the DateDiff function.
WHERE DateDiff(m,@Date,DateField) = 0
This will return anything with a matching month and year.
SELECT * FROM yourtable WHERE yourtimestampfield LIKE 'AAAA-MM%';
Where AAAA
is the year you want and MM
is the month you want
참고URL : https://stackoverflow.com/questions/851236/where-clause-to-find-all-records-in-a-specific-month
'programing tip' 카테고리의 다른 글
'less'명령을 사용하는 동안 Unix에서 특수 문자 표시 (0) | 2020.11.11 |
---|---|
CLR 유형과 EDM 유형의 매핑은 EF 6 & 5에서 모호합니다. (0) | 2020.11.11 |
git 저장소를 복제하는 Python 방법 (0) | 2020.11.10 |
Apache에서 인코딩 된 슬래시를 허용해야합니다. (0) | 2020.11.10 |
취급 방법 (0) | 2020.11.10 |