按ID分组结果并创建新列

时间:2012-11-28 02:36:00

标签: mysql sql

我有一张看起来像下面的表......

id           price             condition         sell
21039        20.40             new               0 
21039        20.41             used              1
12378        10.40             new               1
12378        5                 used              0
45898        30.30             new               1
45898        12.20             used              0

注意:每个ID只会有1个新值和使用值)

我要做的是将具有相同ID号的所有行分组,但在此过程中为每个条件创建新列,这应该看起来像......

id           new_price         new_sell          used_price         new_sell
21039        20.40             0                 20.41              1
12378        10.40             1                 5                  0
45898        30.30             1                 12.20              0

我提出的所有内容都是以下查询,看起来很傻

SELECT id, price, condition, 
IF(price > 3, 1, 0)  AS sell
FROM products 
GROUP BY id 

如何获得第二张桌子所需的效果。

1 个答案:

答案 0 :(得分:3)

这称为数据透视表。对于您需要生成的每个列,使用一系列CASE语句以及聚合MAX()SUM()来消除NULL并将其折叠为单行。

SELECT
  id,
  SUM(CASE WHEN `condition` = 'new' THEN price ELSE 0 END) AS new_price,
  SUM(CASE WHEN `condition` = 'new' THEN sell ELSE 0 END) AS new_sell,
  SUM(CASE WHEN `condition` = 'used' THEN price ELSE 0 END) AS used_price,
  SUM(CASE WHEN `condition` = 'used' THEN sell ELSE 0 END) AS used_sell
FROM 
  products
GROUP BY id

如果没有SUM()GROUP BY,您仍会获得每id行2行,每行有一半的列(condition中不匹配CASE } {} NULLSUM()(在这种情况下也可以使用MAX())消除NULL并生成一行,因为聚合函数排除NULL值,而GROUP BY将行按id分组。 / p> SQLFiddle.com上的

Here is a working sample

评论后更新:

要根据sell计算price,只需替换sell CASE语句中的条件:

SELECT
  id,
  SUM(CASE WHEN `condition` = 'new' THEN price ELSE 0 END) AS new_price,
  SUM(CASE WHEN `condition` = 'new' AND price > 3 THEN 1 ELSE 0 END) AS new_sell,
  SUM(CASE WHEN `condition` = 'used' THEN price ELSE 0 END) AS used_price,
  SUM(CASE WHEN `condition` = 'used' AND price > 3 THEN 1 ELSE 0 END) AS used_sell
FROM 
  products
GROUP BY id

Updated sample...