Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert multiple rows into one row with multiple columns using Pivot in SQL Server when data having NULL values

I have a table from which I want to get data under some conditions. I am getting data with below query.

SELECT track,
       ytd,
       weekno,
       [unit] 
FROM SMIrawdataFinal 
WHERE unit IS NOT NULL AND tracktype='focus' AND track='A' AND ytd IS NOT NULL

Original table (data) is like below.

track   ytd    weekno    unit
A      (Blank)   1        1
A      (Blank)   2        2
A      (Blank)   3        3
A        19      5        5
A      (Blank)   4        4

I got below data using PIVOT in sql server. My problem is how can I remove null values and get the same data in one single row.

autoId  track   ytd   col4   col3   col2    col1    
-------------------------------------------------
1         A   (Blank)  NULL    4      3       2  
2         A     19     5     NULL    NULL    NULL

Below is my SQL Query:

SELECT * 
FROM (
    SELECT track,ytd,weekno,[unit]
    FROM SMIrawdataFinal
    WHERE album = 'XYZ' 
        AND unit IS NOT NULL
        AND tracktype='focus' 
        AND track='A' 
        AND ytd IS NOT NULL
    ) as s 
PIVOT(
    SUM(unit) 
    FOR weekno in ([5],[4],[3],[2])
)AS pivot1
like image 812
Abhi Avatar asked Jul 16 '15 06:07

Abhi


Video Answer


1 Answers

Use a group by with SUM to get the desired output:

    SELECT track, 
    SUM(ISNULL(ytd, 0)) AS [ytd], 
    SUM(ISNULL([5], 0)) AS [5],
    SUM(ISNULL([4], 0)) AS [4],
    SUM(ISNULL([3], 0)) AS [3],
    SUM(ISNULL([2], 0)) AS [2]
    FROM (SELECT track,ytd,weekno,[unit]
    FROM SMIrawdataFinal where album = 'XYZ' 
            AND unit IS NOT NULL
            AND tracktype='focus' 
            AND track='A')    as s PIVOT
    (SUM(unit) FOR weekno in ([5],[4],[3],[2]))AS pivot1
    GROUP BY track

Output:

    track   | ytd   | 5 | 4  | 3    | 2
    --------------------------------
    A       | 19    | 5 | 4  | 3    | 2
like image 66
ashim Avatar answered Oct 27 '22 11:10

ashim