我有以下结果集:
类型 | 方法 | 数量
Type1 现金金额
Type1 支票金额
Type2 现金金额
Type2 支票金额
Type3 现金金额
Type3 支票金额
我想让它看起来像这样:
类型 | 现金 | 查看
类型1金额 金额 类型2 金额
金额类型
3 金额 金额
如何在 T-SQL 中实现这一点(2005 语法正常)?我需要按类型旋转 (1, 2, 3...)
这是 PIVOT 的尝试:
select *
from YourTable
PIVOT (sum(amount) FOR Method in (Cash,Check)) as Y
鉴于它只有两列,可以尝试连接:
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'
或者更好:
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
如果合适,将 ELSE 0 添加到 CASE 语句中。
这种形式比 PIVOT 运算符更灵活,不需要 FULL JOIN。只是直接聚合。