在下面的视图中,我不希望在where条件中指定实际日期,而是希望sql server将June和May识别为最新月份和(最新月份-1),因为视图会按月刷新并且最近一个月也是如此(最近一个月-1)。
PS: - 表中的最新报告月份为6月
SELECT (A.[First Name])
,A.[Last Name]
,A.[Report Month]
FROM (
(
SELECT DISTINCT [First Name]
,[Last Name]
,[Report Month]
,[Bill To Code]
,[Region]
,[Area]
FROM dbo.Data
WHERE (
[Report Month] BETWEEN '2015-06-01'
AND '2015-06-30'
AND [FTE Status] = 'Inactive'
)
) A INNER JOIN (
SELECT DISTINCT [First Name]
,[Last Name]
,[Report Month]
,[Bill To Code]
,[Region]
,[Area]
FROM dbo.Data
WHERE (
[Report Month] BETWEEN '2015-05-01'
AND '2015-05-31'
AND [FTE Status] = 'Active'
)
) B ON A.[First Name] = B.[First Name]
AND A.[Last Name] = B.[Last Name]
)
谢谢你,刚学会了如何在SO中更好地格式化。感谢Sean.Learning来自我的错误家伙.. :)
答案 0 :(得分:0)
怎么样:
SELECT MAX(MONTH(Report_Month))
FROM YourTable
GROUP BY YEAR(Report_Month)
HAVING YEAR(Report_Month) = MAX(YEAR(Report_Month))
答案 1 :(得分:0)
尽管你的问题相当含糊,但我认为这正是你要找的。
这将返回YourTable中最长日期的第一天和最后一天。
;with cte as (
select convert(date,left(convert(varchar,Max(Report_Month),112),6) + '01') startDate,
month(Max(Report_Month)) n
from YourTable
union all
select dateadd(month,n,convert(date,convert(varchar,year(startDate)) + '0101')) startDate,
(n+1) n
from cte
where n < month(startDate)
)
select startdate, dateadd(day,-1,dateadd(month,1,startdate)) enddate
from cte