简体   繁体   中英

tsql columns to rows withut pivot /unpivot function

I need to go from columns to rows. Not sure how to go about best way Pivot and Unpivot commands not available on our 2008R2 server. I tried a Union All setup but couldn't seem to get that to work

Type     S100                  S50 (column header row)

Type1    5000.00               56760.00              
Type2    2345.00               87650.00          

To

Denom   Type1        Type2   (column header row)
100     5000.00      2345.00 
50      56760.00     87650.00

You wouldn't want to use PIVOT & UNPIVOT anyway... They are a bigger pain than they're worth. This should do the trick...

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    TypeId CHAR(5),
    s100 MONEY,
    s50 MONEY 
    );
INSERT #TestData(TypeId, s100, s50) VALUES
    ('Type1', 5000.00, 56760.00),           
    ('Type2', 2345.00, 87650.00);

--SELECT * FROM #TestData td;

WITH 
    cte_Unpivot AS (
        SELECT 
            td.TypeId,
            d.Denom,
            d.cValue
        FROM 
            #TestData td
            CROSS APPLY ( VALUES (100, td.s100), (50, td.s50) ) d (Denom, cValue)
        )
SELECT 
    u.Denom,
    Type1 = SUM(CASE WHEN u.TypeId = 'Type1' THEN u.cValue END),
    Type2 = SUM(CASE WHEN u.TypeId = 'Type2' THEN u.cValue END)
FROM 
    cte_Unpivot u
GROUP BY
    u.Denom
ORDER BY 
    u.Denom DESC;

Results...

Denom       Type1                 Type2
----------- --------------------- ---------------------
100         5000.00               2345.00
50          56760.00              87650.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM