使用case返回单行

时间:2014-01-05 21:21:51

标签: mysql

我有一个字段名称ParcelID,一个字段名称ShapeID和Quantity。 ParcelID是外键,ShapeID包含相同的类型,Quantity是每个ShapeID的数量。

ParcelID可以有多个形状 - >这意味着超过一行。

例如:

**ParcelID    ShapeID  Quantity**
1           Square       3
1           Triangle     7
1           Circle       6

我需要一个返回单行的查询,检查ShapeID并显示这些字段的数量:Square_Shape,Triangle_Shape,Circle_Shape。

最终结果:

**ParcelID  Square_Shape, Triangle_Shape, Circle_Shape.**
    1           3            7                 6

这是我尝试过的 - >但没有成功:

SELECT ParcelID,ShapeID,Quantity
case when ShapeID = 'Square' then Quantity end as Square_Shape,
case when ShapeID = 'Triangle' then Quantity end as Triangle_Shape,
case when ShapeID = 'Circle' then Quantity end as Circle_Shape,

FROM sql_stock a

3 个答案:

答案 0 :(得分:1)

您的查询已结束。大多数情况下,您只需要group by和聚合函数:

SELECT ss.ParcelID,
       sum(case when ShapeID = 'Square' then Quantity end) as Square_Shape,
       sum(case when ShapeID = 'Triangle' then Quantity end) as Triangle_Shape,
       sum(case when ShapeID = 'Circle' then Quantity end) as Circle_Shape
FROM sql_stock ss join
     sql_history sh
     on ss.ParcelID = sh.ParcelID
GROUP BY ss.ParcelID;

每当引用列时,都应该使用表别名。我不知道ShapeIdQuantity是来自股票表还是历史表。

此外,如果您希望在没有值时显示0而不是NULL,请在每个else 0子句中添加case

编辑:

OP似乎已更改原始查询以删除历史记录表。然后查询将是:

SELECT ss.ParcelID,
       sum(case when ShapeID = 'Square' then Quantity end) as Square_Shape,
       sum(case when ShapeID = 'Triangle' then Quantity end) as Triangle_Shape,
       sum(case when ShapeID = 'Circle' then Quantity end) as Circle_Shape
FROM sql_stock s
GROUP BY ss.ParcelID;

答案 1 :(得分:1)

SELECT
  ParcelID,
  SUM(IF(ShapeID='Square',Quantity,0)) AS Square_Shape,
  SUM(IF(ShapeID='Triangle',Quantity,0)) AS Triangle_Shape,
  SUM(IF(ShapeID='Circle',Quantity,0)) AS Circle_Shape
FROM sql_stock
GROUP BY ParcelID

对于缺失或重复的值可能非常强大

答案 2 :(得分:0)

自己加入你的桌子:

select t0.ParcelId, t1.Quantity as Square_Shape, t2.Quantity as TriangleShape, t3.Quantity as CircleShape  
from     
sql_stock t0
LEFT JOIN sql_stock t1 ON (t0.ParcelId = t1.ParcelId and t1.ShapeId = 'Square')
LEFT JOIN sql_stock t2 ON (t0.ParcelId = t2.ParcelId and t2.ShapeId = 'Triangle')
LEFT JOIN sql_stock t3 ON (t0.ParcelId = t3.ParcelId and t3.ShapeId = 'Circle')
group by t0.ParcelId, Square_Shape, TriangleShape, CircleShape;