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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With