次の結果セットがあります。
タイプ | メソッド | 額
Type1現金額
Type1小切手額
Type2現金額
Type2小切手額
Type3現金額
Type3小切手額
そして、私はそれを次のようにしたい:
タイプ | 現金 | 小切手
Type1 量 量
Type2 量 量
Type3 量 量
T-SQL (2005 構文は問題ありません) でこれを達成するにはどうすればよいですか? タイプ(1、2、3...)でピボットする必要があります
またはさらに良い:
select
Type
, Cash = sum(case when Method = 'Cash' then Amount end)
, Check = sum(case when Method = 'Check' then Amount end)
from yourtable
group by
Type
必要に応じて、CASE ステートメントに ELSE 0 を追加します。
この形式は、PIVOT 演算子よりも柔軟で、FULL JOIN を必要としません。ただのまっすぐな集計。
PIVOT での試みを次に示します。
select *
from YourTable
PIVOT (sum(amount) FOR Method in (Cash,Check)) as Y
2 つの列しかないことを考えると、結合を試すことができます。
select
type
, cash = a.amount
, check = b.amount
from yourtable a
full join yourtable b on a.type = b.type
where a.method = 'cash' or b.method = 'Check'