Rows Into Columns and Grouping

后端 未结 5 873
慢半拍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 08:05

    Well, here is another pivot :)

    SET NOCOUNT ON
    
    DECLARE @table TABLE
    (   OrganizationName    VARCHAR(20),
        OrganizationID      INT,
        ReceivableStatus    VARCHAR(20),
        InvoiceFee      FLOAT
    )
    
    INSERT INTO @table
    SELECT 'Company A',139,'60-90 days',672.00 UNION
    SELECT 'Company A',139,'60-90 days',1800.00 UNION
    SELECT 'Company A',139,'over 90 days',1440.00 UNION
    SELECT 'Company B',264,'Current',3559.38 UNION
    SELECT 'Company B',264,'60-90 days',3785.50 UNION
    SELECT 'Company C',271,'60-90 days',446.25 UNION
    SELECT 'Company C',271,'over 90 days',637.50 UNION
    SELECT 'Company C',271,'over 90 days',1126.25
    
    --Specify Just the fields you want to return
    ;WITH COMPANYINFO(OrganizationName,OrganizationID,ReceivableStatus,InvoiceFee) AS
        (
        SELECT  OrganizationName,
            OrganizationID,
            ReceivableStatus,
            InvoiceFee
        FROM    @Table AS b 
        )
        SELECT * 
        FROM COMPANYINFO
        PIVOT
            (
            SUM(InvoiceFee)
            FOR ReceivableStatus
            IN ([Current],[60-90 days],[over 90 days])
            )
        AS P
        ORDER BY OrganizationName
    

提交回复
热议问题