0

我在 SQL Server 2008 中有一个表格,格式如下(简化格式):

日期里程费用

我想得到这样的结果

        上周 当前周 差异
英里        

成本

我怎样才能做到这一点?我是否需要枢轴/取消枢轴或什么是实现这一目标的最简单和性能有效的方法。谢谢。

4

1 回答 1

0
SELECT 'Miles' AS Type, SUM(CASE WHEN date = lastweek THEN miles ELSE 0 END) as lastweek
, SUM(CASE WHEN date = thisweek THEN miles ELSE 0 END) as thisweek
SUM(CASE WHEN date = lastweek THEN miles ELSE 0 END) - SUM(CASE WHEN date = thisweek THEN miles ELSE 0 END) as variance
FROM yourtable
UNION
SELECT 'Cost' AS Type, SUM(CASE WHEN date = lastweek THEN cost ELSE 0 END) as lastweek
, SUM(CASE WHEN date = thisweek THEN cost ELSE 0 END) as thisweek
SUM(CASE WHEN date = lastweek THEN cost ELSE 0 END) - SUM(CASE WHEN date = thisweek THEN cost ELSE 0 END) as variance
FROM yourtable

这不是 100% 正确,但语法应该是正确的,并且应该让您非常接近您正在寻找的内容

于 2013-02-18T22:20:15.987 回答