简体   繁体   中英

SQL Server : merge two rows into one

I wrote the this T-SQL query:

SELECT 
    B.[Year], E.[Description] as GLClass, 
    D.Code, D.[GLDescription], 
    SUM(A.Jan) AS Jan, 
    SUM(A.Feb) AS Feb, 
    SUM(A.Mar) AS Mar, 
    SUM(A.Apr) AS Apr
FROM
    GeneralLedgers A 
INNER JOIN
    Years B ON A.YearID = B.ID
INNER JOIN
    CostCenters C ON A.CostCenterID = C.ID
INNER JOIN
    GLCodes D ON A.GLCodeID = D.ID 
INNER JOIN
    GLClassificationTypes E ON D.GLClassificationTypeID = E.ID
WHERE 
    A.YearID = '13' 
GROPU BY 
    B.[Year], D.Code, E.[Description], D.[GLDescription]
ORDER BY 
    D.Code, E.[Description]

It outputs this result:

在此输入图像描述

I want to combine "Freight-in (Go) and Freight Savings" row into a single row and sum the value from column Jan, Feb, Mar, Apr. I was trying to used the Case When clause on the "Code" column to look for '401040110' and '441010300' but still can't figure it out.

How can this be accomplish?

Convert one of the 2 rows into the other for your groupings logic and the rest of the aggregation should work on top of that seamlessly.

SELECT B.[Year]
    ,E.[Description] AS GLClass
    ,case when D.Code = '441010300' then '401040110' else D.Code END    Code
    ,case when D.Code = '441010300' then 'Freight-in (Go)' else  D.[GLDescription] end [GLDescription]
    ,Sum(A.Jan) AS Jan
    ,Sum(A.Feb) AS Feb
    ,Sum(A.Mar) AS Mar
    ,Sum(A.Apr) AS Apr
FROM GeneralLedgers A
INNER JOIN Years B ON A.YearID = B.ID
INNER JOIN CostCenters C ON A.CostCenterID = C.ID
INNER JOIN GLCodes D ON A.GLCodeID = D.ID
INNER JOIN GLClassificationTypes E ON D.GLClassificationTypeID = E.ID
WHERE A.YearID = '13'
GROUP BY B.[Year]
    , case when D.Code = '441010300' then '401040110' else D.Code END   
    , E.[Description]
    , case when D.Code = '441010300' then 'Freight-in (Go)' else  D.[GLDescription] end
ORDER BY 3,2

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