Get current year's records from a view in SQL Server
I have a view called vwMemberPolicyInfo
and I开发者_StackOverflow中文版 need to display all records entered in current year.
My query is :
select
EffectiveDate AS [Month],
count(MemberID) AS Agents,
sum(ActualPremium) AS Premium
from
vwMemberPolicyInfo
Where
EffectiveDate > DATEADD(year, -1, GETDATE())
GROUP BY
EffectiveDate
but it is not working fine it show result:
2010-11-01 00:00:00.000 74 40644.00
2010-07-01 00:00:00.000 86 50418.00
2011-03-08 00:00:00.000 1 744.00
2011-04-08 00:00:00.000 1 0.00
2010-11-02 00:00:00.000 5 2676.00
2011-04-14 00:00:00.000 1 1185.00
2011-02-28 00:00:00.000 7 2988.00
2011-02-23 00:00:00.000 8 8518.00
2011-04-10 00:00:00.000 1 1332.00
2011-04-07 00:00:00.000 3 2544.00
I need only the current year entries to display ..thanks in advance
Try where YEAR(EffectiveDate) = YEAR(GETDATE())
Hope it helps.
SELECT MONTH(EffectiveDate) AS [Month],
count(MemberID) AS Agents,
sum(ActualPremium) AS Premium
FROM vwMemberPolicyInfo
WHERE EffectiveDate >= DATEADD(year, YEAR(GETDATE()) - 1, CAST('0001-01-01' AS DATE))
AND EffectiveDate < DATEADD(year, YEAR(GETDATE()), CAST('0001-01-01' AS DATE))
GROUP BY
MONTH(EffectiveDate)
It's working just fine - it's doing exactly what you told it to - it gives you back all rows that are between today and a year back (e.g. between Apr 15, 2011 and Apr 15, 2010)
What you probably want to achieve is something like this:
SELECT
EffectiveDate AS [Month],
COUNT(MemberID) AS Agents,
SUM(ActualPremium) AS Premium
FROM
dbo.vwMemberPolicyInfo
WHERE
YEAR(EffectiveDate) = 2011
GROUP BY
EffectiveDate
This will return only rows from the year 2011.
select
EffectiveDate AS [Month],
count(MemberID) AS Agents,
sum(ActualPremium) AS Premium
from
vwMemberPolicyInfo
Where
dateadd(year,0,EffectiveDate) = DATEADD(year, 0, GETDATE())
GROUP BY
EffectiveDate
dateadd(year,0,EffectiveDate) = DATEADD(year, -1, GETDATE())
dateadd(year,-1,EffectiveDate) = DATEADD(year, -1, GETDATE())
精彩评论