根据当前日期,我需要在WHERE
条件中设置案例。
select
count(id)
from
table1
case
when (DAY(GETDATE())) between 1 and 15
Then created_date between (getdate()-DAY(GETDATE())+1) and (getdate()+15-DAY(GETDATE()))
else created_date between (getdate()+16-DAY(GETDATE())) and (getdate()+31-DAY(GETDATE()))
End
但它对我不起作用。
例如,
表1:
Id App_Name Created_Date
1 app1 2016-12-05
2 app2 2016-12-10
3 app3 2016-12-16
4 app4 2016-12-25
5 app5 2016-12-28
今天的日期是2016-12-15,所以我需要在2016-12-01到2016-12-15之间采取created_date。
预期输出为" 2"
答案 0 :(得分:0)
您可以尝试使用嵌套的CASE
表达式以及条件聚合:
SELECT CASE WHEN DAY(GETDATE()) <= 15 THEN
SUM(CASE WHEN created_date BETWEEN (getdate()-DAY(GETDATE())+1) AND
(getdate()+15-DAY(GETDATE()))
THEN 1 ELSE 0 END)
ELSE
SUM(CASE WHEN created_date BETWEEN (getdate()+16-DAY(GETDATE())) AND
(getdate()+31-DAY(GETDATE()))
THEN 1 ELSE 0 END)
END AS summary
FROM table1
答案 1 :(得分:0)
这样做的简单方法。工作完美。试一次
SELECT CASE
WHEN (DAY(GETDATE())) < 16 THEN
(Select Count(1) from SEP_RetailStore WITH (NOLOCK) WHERE DAY(CreateDate) BETWEEN 1 and 15)
ELSE (Select Count(1) from SEP_RetailStore WITH (NOLOCK) WHERE DAY(CreateDate) >= 16)
END