MySQL row into number of columns and sum

后端 未结 3 1902
深忆病人
深忆病人 2021-01-17 05:55

Could somebody help with my SQL?

I have a table with records such as:

ID | Car_num | Service | Price
---+---------+---------+------
1  | 001     | sh         


        
相关标签:
3条回答
  • 2021-01-17 06:22
    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

    0 讨论(0)
  • 2021-01-17 06:34

    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;
    
    0 讨论(0)
  • 2021-01-17 06:41

    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
    
    0 讨论(0)
提交回复
热议问题