Rows Into Columns and Grouping

后端 未结 5 864
慢半拍i
慢半拍i 2021-02-06 07:28

I have a query that looks like this:

SELECT OrganizationName, OrganizationID, ReceivableStatus, InvoiceFee
FROM v_InvoicesFreelanceOutstanding
ORDER BY Organizat         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 07:51

    This looks like a job for pivot if you're using SQL Server 2005 or later.

    EDIT:

    Since you already know about pivot, you know it does almost what you need.

    You already have the following query:

    SELECT
        MAX(OrganizationName) as OrganizationName,
        OrganizationID,
        ReceivableStatus,
        SUM(InvoiceFee) as TotalDue
    FROM v_InvoicesFreelanceOutstanding
    GROUP BY OrganizationID, ReceivableStatus
    

    Which gives you the current, 30-60, 60-90 and 90+ parts that you need. If you pivot that, you get everything you need except for your total. So just throw in the total:

    (SELECT
        MAX(OrganizationName) as OrganizationName,
        OrganizationID,
        ReceivableStatus,
        SUM(InvoiceFee) as TotalDue
    FROM v_InvoicesFreelanceOutstanding
    GROUP BY OrganizationID, ReceivableStatus)
    UNION
    (SELECT
        MAX(OrganizationName) as OrganizationName,
        OrganizationID,
        'Total' AS ReceivableStatus,
        SUM(InvoiceFee) as TotalDue
    FROM v_InvoicesFreelanceOutstanding
    GROUP BY OrganizationID)
    

    Pivot on this result and you should get the output you want:

    SELECT *
    FROM 
        [the query above]
    PIVOT (
        SUM(TotalDue)
        FOR ReceivableStatus IN ([Current],[30-60 days],[60-90 days],[over 90 days],[Total]) 
    )
    

提交回复
热议问题