枚举或计数行JOIN MySql

时间:2015-01-22 21:17:21

标签: mysql group-by

我有两个表,taskstep

task表的示例

^ TaskID  ^ OperID  ^ StepID  ^ Status    ^
| 10      | 10      | 10      | Finished  |
| 11      | 10      | 20      | Active    |
| 12      | 20      | 10      | Active    |
| 13      | 30      | 10      | Finished  |
| 14      | 40      | 10      | Finished  |
| 15      | 10      | 30      | Finished  |
| 16      | 30      | 20      | Active    |
| 17      | 40      | 20      | Active    |
| 18      | 10      | 40      | Active    |
| 19      | 30      | 30      | Active    |

step表的示例。

^ StepID  ^ StepName  ^
| 10       | Step1     |
| 20       | Step2     |
| 30       | Step3     |
| 40       | Step4     |

我想从Task中枚举Active StepName,按OperID分组,换句话说,我需要这样的输出。

^ OperID  ^ StepName  ^ OrderID  ^
| 10      | Step2     | 1       |
| 10      | Step3     | 2       |
| 10      | Step4     | 3       |
| 20      | Step1     | 1       |
| 30      | Step2     | 1       |
| 30      | Step2     | 2       |
| 40      | Step2     | 1       |

我在another article中读到会话变量,但我无法使其发挥作用。

SELECT
   T.OperID,
   S.StepName,
   @Order := IF(@StepName = S.StepName, @Order + 1, 1) AS 'Order',
   @StepName := S.StepName 
FROM
   task AS T
   INNER JOIN step AS S ON S.StepID = T.StepID
WHERE T.Status = 'Active'
ORDER BY OperID

这是一些SQLFiddle http://www.sqlfiddle.com/#!2/71316/2

我不知道自己做错了什么。欢迎任何帮助。

1 个答案:

答案 0 :(得分:0)

你正在比较错误的事情:

@Order := IF(@Order = S.StepName, @Order + 1, 1) AS 'Order',
             ^^^^^---should probably be @StepName

现在,您正在比较您在" StepName'中的字符串构建的整数值。