如何在使用数据透视表后的月份之间插入行

How to insert rows between months after using pivot

我现在一直在使用 SAP Business One,此刻我对如何实现所需的查询输出感到困惑。 所需的输出将像

SLPName | Customer Name | Jan    | Jan-chrgs | Feb    | Feb-chrgs | Mar    | Mar-chrgs 
slp1    | cust1         | 123.00 | 30.00     | 230.00 | 40.00     | 150.00 | 35.00

到目前为止所做的就是这个,它完美地工作但是没有费用(运费,维修费等)。

SELECT SRNAMe, Customer, 
 ISNULL([1],0) as [Jan],
 ISNULL([2],0) as [Feb],
 ISNULL([3],0) as [Mar],
 ISNULL([4],0) as [Apr]

FROM (SELECT T2.SlpName SRNAMe,T1.CARDNAME Customer, SUM(T1.DocTotal) as Total,MONTH(T1.Docdate) as [month] 
    FROM ORDR T1 INNER JOIN OSLP T2 ON T2.SlpCode=T1.SlpCode 
    LEFT OUTER JOIN RDR3 T3 ON T3.DocEntry=T1.DocEntry
    WHERE T1.DocDate BETWEEN '1.1.17' AND '4.30.17'
    AND T1.CANCELED='N' AND T1.U_StatusCancel='N' 
    GROUP BY T2.SlpName,T1.CardName, T1.DocDate) S
              PIVOT  (SUM(S.[Total])  FOR [month] IN ([1],[2],[3],[4])
) P Order By P.SRNAME, P.Customer

我当时的逻辑是

SELECT SRNAMe, Customer, 
 ISNULL([1],0) as [Jan], column as jan-chrg,
 ISNULL([2],0) as [Feb], column as feb-chrg,
 ISNULL([3],0) as [Mar], column as mar-chrg,
 ISNULL([4],0) as [Apr], column as apr-chrg

我不知道其余的,也许把那些总费用放在 pivot 里,但似乎行不通。

如果你得到我想要的,请帮忙。谢谢

经过日思夜想,我终于找到了自己的答案。并希望这对你们也有帮助(你们知道,对于想法)。

SELECT SRNAMe, Customer, 
     ISNULL([1],0) as [Jan], ISNULL(jancharge,0) as [Charge],
     ISNULL([2],0) as [Feb], ISNULL(febcharge,0) as [Charge],
     ISNULL([3],0) as [Mar], ISNULL(marcharge,0) as [Charge],
     ISNULL([4],0) as [Apr], ISNULL(jancharge,0) as [Charge]
    FROM (SELECT T2.SlpName SRNAMe,T1.CARDNAME Customer, (SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=1 AND T8.CardName=T1.CardName) jancharge,
    (SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=2 AND T8.CardName=T1.CardName) febcharge,
    (SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=3 AND T8.CardName=T1.CardName) marcharge,
    (SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=4 AND T8.CardName=T1.CardName) aprcharge, SUM(T1.DocTotal) as Total,MONTH(T1.Docdate) as [month] 
        FROM ORDR T1 INNER JOIN OSLP T2 ON T2.SlpCode=T1.SlpCode 
        LEFT OUTER JOIN RDR3 T3 ON T3.DocEntry=T1.DocEntry
        WHERE T1.DocDate BETWEEN '1.1.17' AND '4.30.17'
        AND T1.CANCELED='N' AND T1.U_StatusCancel='N' 
        GROUP BY T2.SlpName,T1.CardName, T1.DocDate) S
                  PIVOT  (SUM(S.[Total])  FOR [month] IN ([1],[2],[3],[4])
    ) P Order By P.SRNAME, P.Customer