下面请找我的选择。此选择的结果如下:
fecha1 columna_1 columna_2
09.07.2014 10.00000000 3.00000000
10.07.2014 12.20000000 5.06000000
11.07.2014 15.56600000 9.26240000
12.07.2014 20.18864000 27.35320192
15.07.2014 28.60184480 22.85988716
我的问题是:我想在下面的选择结果中添加一个额外的行。该行应包括:
fecha1 =“fecha1”栏中显示的第一天前一天
columna_1 = 0
columna_2 = 0
我可以这样做吗?
这是实际选择:
DECLARE @sales TABLE
(codigo VARCHAR(10) NOT NULL,
fecha DATE NOT NULL,
diferencia NUMERIC(10, 2) NOT NULL);
INSERT INTO @sales(codigo, fecha, diferencia)
VALUES ('q', '20140708', 51),
('q', '20140712', 0.03),
('q', '20140712', 0.033),
('q', '20140712', 0.04),
('q', '20140811', 0.03),
('q', '20140812', 0.01),
('q', '20140815', 0.05),
('q', '20140815', 0.06),
('q', '20140815', 0.02),
('q', '20140114', 0.07),
('q', '20140714', 0.024),
('q', '20140714', 0.024),
('x', '20140709', 0.025),
('x', '20140710', 0.016),
('x', '20140711', 0.036),
('x', '20140712', 0.023),
('x', '20140712', 0.035),
('x', '20140715', 0.057),
('c', '20140709', 0.097),
('c', '20140710', 0.0197),
('c', '20140711', 0.0297),
('c', '20140712', 0.0397),
('c', '20140715', 0.071);
;with ctesource as
(
select
codigo,diferencia,
fecha,
sum( log( 1e0 + diferencia ) ) over ( partition by codigo order by fecha rows unbounded preceding) as LogAssetValue
from
@sales
WHERE codigo IN ( 'c', 'x') and fecha > DATEADD(month, -24, getdate())
)
select convert(varchar, fecha, 104) AS fecha1,
CAST(SUM(Case codigo when 'c' then (exp(LogAssetValue)-1)*100 ELSE 0 END) AS numeric(16, 8)) as columna_1,
CAST(SUM(Case codigo when 'x' then (exp(LogAssetValue)-1)*100 ELSE 0 END) AS numeric(16, 8)) as columna_2
from ctesource
GROUP BY fecha
order by fecha;
非常感谢!!!!!!
答案 0 :(得分:0)
在SQL Server中使用varchar
总是包含长度。实现目标的一种方法是使用union all
:
(select convert(varchar(255), fecha, 104) AS fecha1,
CAST(SUM(Case codigo when 'c' then (exp(LogAssetValue)-1)*100 ELSE 0 END) AS numeric(16, 8)) as columna_1,
CAST(SUM(Case codigo when 'x' then (exp(LogAssetValue)-1)*100 ELSE 0 END) AS numeric(16, 8)) as columna_2
from ctesource
GROUP BY fecha
) union all
(select convert(varchar(255), dateadd(-1, day, min(fecha)), 104),
0, 0
from ctesource
)
order by fecha1;