Sql 在枢轴上拆分贷项和借项

Sql 在枢轴上拆分贷项和借项,sql,sql-server,tsql,pivot,Sql,Sql Server,Tsql,Pivot,我有以下疑问: DECLARE @cols AS varchar(8000) = '' DECLARE @selectcols AS varchar(8000) = '' DECLARE @query AS varchar(8000) = '' SELECT @cols = @cols + QUOTENAME(Type) + ',' FROM (select distinct [Type] from #temp) as tmp order by Type SELECT @cols = LEFT

我有以下疑问:

DECLARE @cols AS varchar(8000) = ''
DECLARE @selectcols AS varchar(8000) = ''
DECLARE @query AS varchar(8000) = ''

SELECT @cols = @cols + QUOTENAME(Type) + ',' FROM (select distinct [Type] from #temp) as tmp order by Type
SELECT @cols = LEFT(@cols, LEN(@cols) - 1) 

SELECT @selectcols = @selectcols + 'ISNULL(' + QUOTENAME(Type) + ',0) as ' + QUOTENAME(Type) +',' FROM (select distinct Type from #temp) as tmp order by Type
SELECT @selectcols = LEFT(@selectcols, LEN(@selectcols) - 1) 

SET @query = 
'
select 
    PostDate,
    Status,
    Account,
    ' + @selectcols + '
from
    #temp
    pivot
    (
      sum(Amount)
      for Type in (' + @cols + ')
    ) p
'

EXECUTE (@query)
它给出了以下结果:

然而,我需要做的是针对所有不同的类型,在不同的列中显示贷项和借项,即1类贷项、2类借项、1类贷项、2类借项等

我知道我可以做类似的事情:

CASE WHEN amount >= 0 THEN amount
     ELSE NULL
END AS debit ,
CASE WHEN amount < 0 THEN amount
     ELSE NULL
END AS credit

我不明白为什么需要动态SQL。在这种情况下,它看起来像条件聚合:

select postdate, status, account,
       sum(case when type = 1 and amount > 0 then amount end) as type1_credit,
       sum(case when type = 1 and amount < 0 then amount end) as type1_debit,
       sum(case when type = 2 and amount > 0 then amount end) as type2_credit,
       sum(case when type = 2 and amount < 0 then amount end) as type2_debit
from #temp
group by postdate, status, account;

当然,如果您不知道数据中的类型,那么您可以将上述内容调整为动态SQL。

公平地说,Gordon,我不知道这些类型,因此认为有一种更干净的方法可以通过pivot完成上述操作。
select postdate, status, account,
       sum(case when type = 1 and amount > 0 then amount end) as type1_credit,
       sum(case when type = 1 and amount < 0 then amount end) as type1_debit,
       sum(case when type = 2 and amount > 0 then amount end) as type2_credit,
       sum(case when type = 2 and amount < 0 then amount end) as type2_debit
from #temp
group by postdate, status, account;