0

会计表具有如下所示的示例数据:(AcctgHeads 可能比此处显示的更多)

+-------+-----------+--------+------+
| 贷款 | 会计主管 | 金额 | D_C |
+-------+-----------+--------+------+
| 1 | 校长 | 10000 | D |
| 1 | 校长 | 500 | C |
| 1 | 现金 | 10000 | C |
| 1 | 现金 | 500 | D |
| 2 | 校长 | 5000 | D |
| 2 | 现金 | 5000 | C |
| 2 | 现金 | 300 | D |
| 2 | 校长 | 300 | C |
| 1 | 到期 | 50 | D |
| 1 | 收入 | 50 | C |
+-------+-----------+--------+------+

所需的输出是:

+--------+-------------+-------------+--------+-- ---+------------+----------+-------------+---------- ---+
| 贷款 | 校长_D | 校长_C | 现金_D | 现金_C | IntDue_D | IntDue_C | 收入_D | 收入_C |
+--------+-------------+-------------+--------+-- ---+------------+----------+-------------+---------- ---+
| 1 | 10000 | 500 | 500 | 10000 | 50 | 0 | 0 | 50 |
| 2 | 5000 | 300 | 300 | 5000 | 0 | 0 | 0 | 0 |
+--------+-------------+-------------+--------+-- ---+------------+----------+-------------+---------- ---+

完成此任务的查询是什么?

在此先感谢您的帮助。

4

1 回答 1

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

SQL 演示

于 2013-04-20T03:16:23.817 回答