我想根据CASE
语句选择数据。示例如下:
select Id, name, address,
case when
department = CIS then @first
else @firstnew
end as "Date"
这里@first
应该是下面查询的输出
DECLARE @first date, @second date, @current date, @new date;
SET @second='2015-12-15'
SET @new='2015-08-10'
SET @current = CONVERT(VARCHAR(10),GETDATE(),110)
SET @first = '2015-08-15'
WHILE @first <= @second
BEGIN
SET @first = @new
WHILE @first <= @second
BEGIN
if @first >= @current
break;
SET @first = DATEADD(MONTH,1,@first)
END;
break;
END;
如果部门等于CIS的情况,是否可以使用上述查询输出@first
的值作为第一个SELECT
语句的结果?
答案 0 :(得分:1)
我认为@firstnew
等于DATEADD(MONTH, -1, DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new)))
,所以您的查询可以是这样的:
SELECT Id, name, address,
CASE WHEN department = 'CIS' THEN
@first
CASE WHEN @first > @second THEN
@first
CASE WHEN @new > @second THEN
@new
CASE WHEN DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new)) < @second THEN
DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new))
ELSE
DATEADD(MONTH, -1, DATEFROMPARTS(YEAR(@second), MONTH(@second), DAY(@new)))
END AS [Date]
...