Dec 31, 2010

Display column of different rows as column of a single row in SQL Server

Problem
Displaying column value of different rows in a single row with a separator comma, hyphen, semicolon etc.

Solution
In the below solution, refer the table "PRODUCT". In the table there are multiple products for a client and we are trying to display products as comma separated value for each client as a single row.

Table and Data Script
CREATE TABLE PRODUCT (
      ClientNumber    VARCHAR(50)
    , ClientName    VARCHAR(50)
    , Product        VARCHAR(50)
)

INSERT INTO PRODUCT
SELECT '100SON', 'Sony', 'TV' UNION ALL
SELECT '100SON','Sony', 'DVD Player' UNION ALL
SELECT '100SON','Sony', 'Cell Phone' UNION ALL
SELECT '200KEN','Kenmoore', 'Microwave' UNION ALL
SELECT '200KEN','Kenmoore', 'Dryer'
Table Data
Table Data

Now, lets write a query to display the data of product as a single row on the basis of Client Number and Client Name.

SELECT ClientNumber, ClientName
       , STUFF(( SELECT ',' + Product
                 FROM PRODUCT b
                 WHERE a.ClientNumber = b.ClientNumber
                 FOR XML PATH('')
         ), 1, 1, '') AS ProductList
FROM  PRODUCT a
GROUP BY ClientNumber, ClientName
OUTPUT
Output
redapple24

Dec 6, 2010

Cumulative Sum in Oracle

In this post, I am sharing the code to calculate Cumulative sum in Oracle

Table Sample Data

Table Sample Data

Query to get Cumulative Sum of Amount on the basis of Type

SELECT NUM
       , DECODE(TYPE, 'DR', AMOUNT)
       , DECODE(TYPE, 'CR', AMOUNT)
       , SUM (DECODE(TYPE, 'CR', AMOUNT, -1 * AMOUNT))
         OVER (ORDER BY NUM ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
         AS BALANCE
FROM TBL
GROUP BY NUM, TYPE, AMOUNT
Output
Output