需要帮助。我想根据日期函数获取动态名称列表。上个月,上个月-1,上个月-2。简单地从上个月,从上个月 - 2和上个月 - 3
获得前10名约翰
由于
答案 0 :(得分:1)
SELECT * FROM
(
SELECT Datediff(Month,Date,GETDATE()) Mon
,ROW_NUMBER()Over (partition by Datediff(Month,date,GETDATE()) ORDER BY date) RNO ,*
FROM Table
)A
WHERE mon <=3 and mon > 0 and rno<=10
答案 1 :(得分:0)
让我假设有一个名为“Table1”的表名为date_created&amp;值。
所以你的查询可能是: (1)上个月
select * from Table1
WHERE date_created>=DATEADD(month, datediff(month, 0, getdate())-1, 0)
and date_created<DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
order by Value desc
(2)过去两个月
select * from Table1
WHERE date_created>=DATEADD(month, datediff(month, 0, getdate())-2, 0)
and date_created<DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
order by Value desc
(3)过去3个月
select * from Table1
WHERE date_created>=DATEADD(month, datediff(month, 0, getdate())-3, 0)
and date_created<DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
order by Value desc
答案 2 :(得分:0)
如果你有标记表,那么使用它来获取前10个月的名称:
SELECT TOP 10 n AS A, DATENAME(mm, DATEADD(mm, 0 - n, GETDATE())) FROM tally;
要创建标记表,请参阅SQL ServerCentral