MySQL行分为列数和总和

时间:2016-11-03 07:13:40

标签: mysql sql

有人可以帮助我的SQL吗?

我有一张包含以下记录的表:

ID | Car_num | Service | Price
---+---------+---------+------
1  | 001     | shower  | 10
2  | 002     | TV      |  5
3  | 001     | TV      |  5

如何编写SQL查询以获得以下输出?

ID |Car_num | shower | TV
---+--------+--------+---
1  | 001    | 10     | 5
2  | 002    |  0     | 5

3 个答案:

答案 0 :(得分:3)

使用透视查询:

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

答案 1 :(得分:0)

SELECT ROW_NUMBER() OVER(ORDER BY Car_num) Id,Car_num ,ISNULL([TV],0) [TV],ISNULL([shower],0) [shower]

这 (    SELECT Car_num,_Service,ISNULL(Price,0)Price    来自#Table )数据 枢 (   最高(价格)FOR _Service IN([TV],[淋浴]) )AS PVT

答案 2 :(得分:-1)

试试这个:

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;