我有这个脚本:
SELECT
ISNULL([name], 'Total') AS [name]
, [Yesterday]
, [Today]
, [variance]
FROM
(
SELECT
[name],
SUM([yesterday]) AS [yesterday],
SUM([today]) AS [today],
sum(variance) as Variance
FROM mytable
GROUP BY [name] WITH ROLLUP
) AS DT
返回此表:
name |yesterday|today|variance
john | 3 |4 | 0.33
smith | 4 |5 |0.25
daniel| 5 |2 |-0.6
total | 12 |11 |-0.02
其中方差总和实际应为:(11-12)/ 12 = -0.833
如何让我的脚本产生结果而不是总差异列?
预期的数据将是:
name |yesterday|today|variance
john | 3 |4 | 0.33
smith | 4 |5 |0.25
daniel| 5 |2 |-0.6
total | 12 |11 |-0.833
答案 0 :(得分:0)
你试过这个吗?:
SELECT
ISNULL([name], 'Total') AS [name]
, [Yesterday]
, [Today]
, [variance]
FROM
(
SELECT
[name],
SUM([yesterday]) AS [yesterday],
SUM([today]) AS [today],
((SUM([today]) -SUM([yesterday]))/SUM([yesterday])) as Variance
FROM mytable
GROUP BY [name] WITH ROLLUP
) AS DT