|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
[code=sql]USE tempdb
IF OBJECT_ID('TEST') IS NOT NULL
DROP TABLE TEST; --> 如果表TEST不为空,删除表
GO
CREATE TABLE TEST --> 创建表,字段及类型如下
(
id int,
stardate date,
enddate date,
);
GO
INSERT INTO TEST VALUES --> 向表中插入数据
(1,'2011-12-1','2013-11-30'),
(2,'2012-5-1','2012-5-31'),
(3,'2012-7-1','2013-6-30');
GO
--------------------开始查询--------------------
select *,DATEDIFF(day,stardate,enddate)+1 as yearday
from
(
select id,
case
when stardate < '2012-1-1' then '2012-1-1'
when stardate > '2012-12-31' then null
else stardate
end as stardate,
case
when enddate < '2012-1-1' then null
when enddate > '2012-12-31' then '2012-12-31'
else enddate
end as enddate
from test
) as a
--------------------运行结果--------------------
/*
id stardate enddate yearday
----------- ---------- ---------- -----------
1 2012-01-01 2012-12-31 366
2 2012-05-01 2012-05-31 31
3 2012-07-01 2012-12-31 184
(3 行受影响)
*/[/code]
case when 换成 iif 或 switch 即可 |
|