会计表的样本数据如下所示: (可能会有比这里显示的更多的AcctgHeads)
+-------+-----------+--------+-----+ | Loan | AcctgHead | Amount | D_C | +-------+-----------+--------+-----+ | 1 | Principal | 10000 | D | | 1 | Principal | 500 | C | | 1 | Cash | 10000 | C | | 1 | Cash | 500 | D | | 2 | Principal | 5000 | D | | 2 | Cash | 5000 | C | | 2 | Cash | 300 | D | | 2 | Principal | 300 | C | | 1 | IntDue | 50 | D | | 1 | IntIncome | 50 | C | +-------+-----------+--------+-----+
所需的输出是:
+------+-------------+-------------+--------+--------+----------+----------+-------------+-------------+ | Loan | Principal_D | Principal_C | Cash_D | Cash_C | IntDue_D | IntDue_C | IntIncome_D | IntIncome_C | +------+-------------+-------------+--------+--------+----------+----------+-------------+-------------+ | 1 | 10000 | 500 | 500 | 10000 | 50 | 0 | 0 | 50 | | 2 | 5000 | 300 | 300 | 5000 | 0 | 0 | 0 | 0 | +------+-------------+-------------+--------+--------+----------+----------+-------------+-------------+
要完成此任务的查询是什么?
提前感谢您的帮助。
答案 0 :(得分:1)
试试这个:(假设你的acctghead有固定数量的值,如图所示)
select loan,
isnull(Principal_D,0) Principal_D,
isnull(Principal_C,0) Principal_C,
isnull(Cash_D,0) Cash_D,
isnull(Cash_C,0) Cash_C,
isnull(IntDue_D,0) IntDue_D,
isnull(IntDue_C,0) IntDue_C,
isnull(IntIncome_D,0) IntIncome_D,
isnull(IntIncome_C,0) IntIncome_C
from
(select loan, amount, AcctgHead + '_' + D_C As AcctgHeadDC from t) t
pivot
(
max(amount) for AcctgHeadDC in
(Principal_D,Principal_C,Cash_D,Cash_C,
IntDue_D,IntDue_C,IntIncome_D,IntIncome_C)
) p