简体   繁体   中英

Two Rows into one row in SQL

I had an output for the following like this in 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

How will i display these rows into one Row:

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

Please help

another way is to use PIVOT() function

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

Group only by item code and put the CASE inside the 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

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