(存储过程)将结果2行合并为1行结果

时间:2017-03-06 02:39:52

标签: sql stored-procedures

我可以将结果第3行和第4行合并为1行记录吗?

select @fYear as [Year],
    (case when main.Description in ('Kecil', 'Tanah') then 'JK'
         else main.Description
    end) as description,

    --CardType,
    sum(case when MONTH(blue.AppliedDate) = 1 then 1 else 0 end) as Jan_Collection,
    sum(case when MONTH(blue.AppliedDate) = 2 then 1 else 0 end) as Feb_Collection,
    ...

    from tblR as main
    left join tblP as b on  main.requestorid = b.requestorid
    left join tblB as blue on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear

    group by  (case when main.Description in ('Kecil', 'Tanah') then 'JK'
           else main.Description
      end)

此输出如下: https://gyazo.com/d930cb2aee92f90ba31dd543d6ca64f3

但我可以将记录第3行和第4行显示为像JK这样的1条记录,如下图所示:https://gyazo.com/a89ed2fa04b51135bf8601d59d4af0b2

感谢。

1 个答案:

答案 0 :(得分:1)

如果您想要结合这些特定的descriptions,您可以在caseselect中使用group by

select @fYear as [Year],
       (case when description in ('kecil', 'Tanah') then 'JK'
             else main.Description
        end) as Description,
       sum(case when MONTH(blue.AppliedDate) = 1 then 1 else 0 end) as Jan_Collection,
       sum(case when MONTH(blue.AppliedDate) = 2 then 1 else 0 end) as Feb_Collection,
       ...
from tblR main left join
     tblP b
     on  main.requestorid = b.requestorid left join
     tblB
     blue
     on b.partyid = blue.partyid and YEAR(blue.AppliedDate) = @fYear
group by (case when description in ('kecil', 'Tanah') then 'JK'
               else main.Description
          end)