问题描述
您好,我正在寻找简单的方法,如何获取上个月的数据。我得到了这个代码,但它在 1 月份不起作用(结果是 12 2021,我需要 12 2020)
select month(dateadd(month,-1,getdate())),year(getdate())
解决方法
大概,您有某种日期列。
在 SQL Server 中,您可以使用 datediff()
来表达这个概念:
where datediff(month,datecol,getdate()) = 1
然而,这不是“sargable”,这意味着它会阻止使用索引。所以,我会建议:
where datecol < datefromparts(year(getdate()),month(getdate()),1) and
datecol >= dateadd(month,1,datefromparts(year(getdate()),1))
如果你只是想要上个月的第一天,你可以使用:
dateadd(month,1))
,
使用此处给出的答案:How can I select the first day of a month in SQL?
SELECT dateadd(month,-1,DATEADD(month,DATEDIFF(month,getdate()),0)) as previousmonth;
输出: 2020-12-01 00:00:00.000
,我可以使用 FORMAT function 提供下一个查询:
SELECT
-- get current day in previous month
FORMAT(dateadd(month,'yyyy-MM-dd') as current_previousmonth,-- get first of previous month
FORMAT(dateadd(month,'yyyy-MM-01') as first_previousmonth,-- previous month without date
FORMAT(dateadd(month,'yyyy-MM') as previousmonth;
,
给你!
.subarticle{
display:flex;
}
结果:
<article>
<div class="subarticle">
<div class="wrapper">
<img src="img/logo2.jpg" alt="logo s textom good idea" class="goodidea">
<div class="informacie">
<h2 class="SOČ">SOČ</h2>
<p class="datum"><i class="far fa-calendar-times"></i>6.1.2021</p>
<h3>
Stredoškolská odborná činnosť <br> <br>
Prekonaj sám seba a ukáž,že máš talent...
</h3>
<p class="read">ČÍTAŤ VIAC</p>
</div>
</div>
<div class="wrapper">
<img src="img/logo2.jpg" alt="logo s textom good idea" class="goodidea">
<div class="informacie">
<h2 class="SOČ">SOČ</h2>
<p class="datum"><i class="far fa-calendar-times"></i>6.1.2021</p>
<h3>
Stredoškolská odborná činnosť <br> <br>
Prekonaj sám seba a ukáž,že máš talent...
</h3>
<p class="read">ČÍTAŤ VIAC</p>
</div>
</div>
</div>
</article>
您还可以使用 select dateadd(mm,eomonth(getdate())) as [Previous Month]
或 Previous Month
--------------
2020-12-31
函数根据需要设置日期格式。
试试这个
select CASE WHEN month(getdate())>1 THEN month(getdate())-1 ELSE 12 END,
CASE WHEN 月份(getdate())>1 THEN YEAR (getdate()) ELSE YEAR (getdate()) -1 END