2

フォーマットのデータがある場合;

Account  | Period     | Values
Revenue  | 2013-01-01 | 5432
Revenue  | 2013-02-01 | 6471
Revenue  | 2013-03-01 | 7231
Costs    | 2013-01-01 | 4321
Costs    | 2013-02-01 | 5672
Costs    | 2013-03-01 | 4562

そして、次のような結果を得たいです。

Account  | Period     | Values
Margin   | 2013-01-01 | 1111
Margin   | 2013-02-01 |  799
Margin   | 2013-03-01 | 2669
M%       | 2013-01-01 |  .20
M%       | 2013-02-01 |  .13
M%       | 2013-03-01 |  .37

ここで、マージン = 収益 - コスト、M% は各期間の (収益 - コスト)/収益です。

これを達成するさまざまな方法を見ることができますが、すべてが非常に醜いので、この種の複数行の計算に対するエレガントな一般的なアプローチがあるかどうかを知りたいと思いました。

ありがとう

編集

これらの計算のいくつかは、次のように非常に複雑になる可能性があります

フリー キャッシュ フロー = マージン - 運営費 - 設備投資 + 運転資本の変化 + 支払利息

したがって、多くの結合を必要としない一般的な方法を望んでいます。

ありがとう

4

4 に答える 4

2

OK、次のように Max を Case ステートメントに追加します。

with RevAndCost as (revenue,costs,period)
as
(

    select "Revenue" = Max(Case when account="Revenue" then Values else null end),
           "Costs" = MAX(Case when account="Costs" then values else null end),
           period
            from data
    group by period

)

select Margin = revenue-costs,
       "M%" = (revenue-costs)/nullif(revenue,0)
from RevAndCost
于 2013-05-20T15:54:16.270 に答える
1

ここでは、共通テーブル式を使用してデータ テーブルの 2 つのインスタンス間で完全な外部結合を行い、Revenue と Costs を 1 つのテーブルに取り込み、その CTE から選択します。

with RevAndCost as (revenue,costs,period)
as
(
    select  ISNULL(rev.Values,0) as revenue, 
            ISNULL(cost.values,0) as costs, 
        ISNULL(rev.period,cost.period)
    from data rev full outer join data cost
    on rev.period=cost.period
)

select Margin = revenue-costs,
   "M%" = (revenue-costs)/nullif(revenue,0)
from RevAndCost
于 2013-05-20T15:40:24.020 に答える
1

私は次のようにします:

SELECT r.PERIOD, r.VALUES AS revenue, c.VALUES AS cost,
r.VALUES - c.VALUES AS margin, (r.VALUES - c.VALUES) / r.VALUES AS mPct
FROM 
    (SELECT PERIOD, VALUES FROM t WHERE
    ACCOUNT = 'revenue') r INNER JOIN
    (SELECT PERIOD, VALUES FROM t WHERE
    ACCOUNT = 'costs') c ON
    r.PERIOD = c.PERIOD
于 2013-05-20T15:44:58.030 に答える