两行在SQL中排成一行

时间:2013-05-28 05:34:33

标签: sql sql-server-2008

我在sQL server 2008中有以下输出。

select ItemCode,
case when trntype = 'Issued' then sum(qty) end as issuedqty,
case  when trntype = 'Received' then sum(qty) end as receievedqty
from  [View_New]
group by ItemCode,trntype
Order by itemcode 

Code            Recd Qty   Issued Qty
--------------------------------------
10CMSQURSET     NULL       2.0000
10CMSQURSET     56.0000    NULL

我如何将这些行显示在一行中:

Code            Recd Qty   Issued Qty
--------------------------------------
10CMSQURSET 56.0000     2.0000

请帮忙

2 个答案:

答案 0 :(得分:1)

另一种方法是使用PIVOT()函数

SELECT  itemCode,
        Received AS RECEIEVEDQTY,
        Issued AS ISSUEDQTY
FROM
        (
            SELECT  itemCode, trntype, qty
            FROM    View_new
        ) dta
        PIVOT
        (
            SUM(qty)
            FOR trntype IN ([Issued], [Received])
        ) pvt

答案 1 :(得分:0)

仅按项目代码分组,并将CASE放在SUM中:

select ItemCode,
   sum(case when trntype = 'Issued' then qty else 0 end) as issuedqty,
   sum(case  when trntype = 'Received' then qty else 0 end) as receievedqty
from  [View_New]
group by ItemCode
Order by itemcode