Could somebody help with my SQL?
I have a table with records such as:
ID | Car_num | Service | Price
---+---------+---------+------
1 | 001 | sh
SELECT ROW_NUMBER() OVER(ORDER BY Car_num) Id,Car_num ,ISNULL([TV],0) [TV],ISNULL([shower],0) [shower]
FROM ( SELECT Car_num , _Service , ISNULL(Price,0) Price FROM #Table )Data PIVOT ( MAX(Price) FOR _Service IN ([TV],[shower]) )AS PVT
Try this:
SELECT ID, Car_num
, SUM(IF(Service = 'shower', Price, 0)) AS Shower
, SUM(IF(Service = 'TV', Price, 0)) AS TV
FROM your_table
GROUP BY Car_num;
Use a pivot query:
SELECT MIN(ID) AS ID,
Car_num,
MAX(CASE WHEN Service = 'shower' THEN Price ELSE 0 END) AS shower,
MAX(CASE WHEN Service = 'TV' THEN Price ELSE 0 END) AS TV
FROM yourTable
GROUP BY Car_num