如果我从dbo.targetsvssales表中选择全部,我会得到以下结果:
Date | Sales | Targets
_____________________________
2017-01-01 10 10
2017-02-01 19 20
2017-03-01 31 30
2017-04-01 38 40
2017-05-01 49 50
2017-06-01 62 60
2017-07-01 70 70
2017-08-01 75 80
2017-09-01 88 90
2017-10-01 101 100
2017-11-01 105 110
2017-12-01 105 120
我想只选择小于当前日期的销售数据,将未来日期的结果保留为空,但保持目标值不变。所以select语句的结果是:
Date | Sales | Targets
_____________________________
2017-01-01 10 10
2017-02-01 19 20
2017-03-01 31 30
2017-04-01 38 40
2017-05-01 49 50
2017-06-01 62 60
2017-07-01 70 70
2017-08-01 75 80
2017-09-01 88 90
2017-10-01 101 100
2017-11-01 105 110
2017-12-01 NULL 120
这需要能够全年工作,以及具有每周和每日精度的表作为日期列,所以使用
WHERE DATE > GETDATE()
或类似的东西是理想的。任何帮助或建议将不胜感激。
答案 0 :(得分:3)
使用case
定义此列的结果:
CASE WHEN DATE <= GETDATE()
THEN Sales
END AS Sales
注意我已经颠倒了你的逻辑并跳过了else null
,因为如果省略,这仍然是默认的。
有关案例的更多信息:http://modern-sql.com/feature/case
答案 1 :(得分:0)
案例将适用于此问题。
CASE WHEN DATE<=GETDATE() THEN Sales ELSE NULL END
答案 2 :(得分:0)
使用此:
select Date, case when Date > getdate() then NULL else Sales end as Sales, Targets
from dbo.targetsvssales
答案 3 :(得分:0)
您可以使用Cas When语句
select date,
CASE
WHEN Date <= GETDATE()
THEN Sales
else NULL
End as Sales,
targets
from dbo.targetsvssales
答案 4 :(得分:0)
使用ROW_NUMBER
和CASE
:
CREATE TABLE T (
MDate DATE,
Sales INT,
Targetes INT
);
INSERT INTO T VALUES
('2017-01-01', 10 , 10),
('2017-02-01', 19 , 20),
('2017-03-01', 31 , 30),
('2017-04-01', 38 , 40),
('2017-05-01', 49 , 50),
('2017-06-01', 62 , 60),
('2017-07-01', 70 , 70),
('2017-08-01', 75 , 80),
('2017-09-01', 88 , 90),
('2017-10-01', 101, 100),
('2017-11-01', 105, 110),
('2017-12-01', 105, 120);
WITH CTE AS (
SELECT *, ROW_NUMBER () OVER (PARTITION BY Sales ORDER BY MDate) RN
FROM T
)
SELECT MDate, CASE WHEN RN = 1 THEN Sales ELSE NULL END AS Sales, Targetes
FROM CTE;
如果您真的想与GETDATE()
进行比较,那么我建议您使用IIF
或CASE
作为:
SELECT MDate, IIF(IIF(MDate <= GetDate(), Sales, NULL) AS Sales, Targetes
FROM T;
<强> Demo 强>
答案 5 :(得分:0)
DECLARE @targetsvssales AS TABLE ([Date] DATE, Sales MONEY, Targets MONEY)
INSERT INTO @targetsvssales VALUES
('2017-01-01',10,10),
('2017-02-01',19,20),
('2017-03-01',31,30),
('2017-04-01',38,40),
('2017-05-01',49,50),
('2017-06-01',62,60),
('2017-07-01',70,70),
('2017-08-01',75,80),
('2017-09-01',88,90),
('2017-10-01',101,100),
('2017-11-01',105,110),
('2017-12-01',105,120)
SELECT
[Date]
,CASE WHEN [DATE] > GETDATE() THEN NULL ELSE Sales END AS Sales
,Targets
FROM @targetsvssales