MySQL查询在几个条件下聚合术语

时间:2015-06-09 23:03:06

标签: mysql aggregate-functions

从以下数据开始:

clubType   desiredShape   lineDirection
---------------------------------------
driver     straight       left
driver     draw           straight
iron       straight       right
wedge      straight       straight
iron       fade           right
wedge      straight       straight
iron       fade           left
iron       draw           straight

我想写一个可以返回的查询:

  • count desiredShape =“draw”
  • count desiredShape =“straight”
  • count desiredShape =“fade”
  • count lineDirection =“left”
  • count lineDirection =“straight”
  • count lineDirection =“right”

clubType

所以,我尝试过这样的事情:

SELECT
    clubType,
    (SELECT count(*) FROM shots WHERE desiredShape = "fade") as count_DesiredFade,
    (SELECT count(*) FROM shots WHERE desiredShape = "draw") as count_DesiredDraw,
    (SELECT count(*) FROM shots WHERE desiredShape = "straight") as count_DesiredStraight
    ...
FROM shots
GROUP BY clubType

但它不对。不知道如何迭代俱乐部类型并聚合其他计数。

我想结束这样的事情:

clubType   desDraw   desFade   desStraight   lineLeft   lineRight   lineRight
-----------------------------------------------------------------------------
driver     3         2         4             3          2           1
iron       4         1         2             4          2           1
wedge      1         3         2             1          0           2

1 个答案:

答案 0 :(得分:1)

使用布尔表达式返回1(TRUE)或0(FALSE)或NULL。将其包裹在''聚合中,以便获得布尔表达式为TRUE的行的“计数”。

例如:

SUM()

注意:表达式SELECT t.clubType , SUM(t.desiredShape = 'fade') as count_DesiredFade , SUM(t.desiredShape = 'draw') as count_DesiredDraw , SUM(t.desiredShape = 'straight') as count_DesiredStraight , ... FROM shots t GROUP BY t.clubType 等同于

t.desired_shape = 'fade'

或更符合ANSI的

  IF(t.desired_shape = 'fade',1,IF(t.desired_shape IS NULL,NULL,0))