SQL Server:将两行合并为一行

时间:2015-02-26 22:00:58

标签: sql sql-server tsql

我写了这个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]

输出此结果:

enter image description here

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

如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

将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