简体   繁体   English

SQL Server:将两行合并为一行

[英]SQL Server : merge two rows into one

I wrote the this T-SQL query: 我写了这个T-SQL查询:

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. 我想将“Freight-in(Go)和Freight Savings”行合并为一行,并将Jan,Feb,Mar,Apr列中的值相加。我试图在“Code”列上使用Case When子句寻找'401040110'和'441010300',但仍然无法弄明白。

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. 将2行中的一行转换为另一行,用于分组逻辑,其余的聚合应该无缝地在其上工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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