选择一列数据,然后在某个条件为真时计算该列的值

时间:2015-06-09 14:45:52

标签: mysql

假设我有一张这样的表:

project_id | created_by | created    
    1      |      3     | 2015-04-01    
    2      |      3     | 2015-04-07    
    3      |      4     | 2015-05-01    
    4      |      4     | 2015-05-02

我希望选择这些列,然后计算每个项目之前created_by创建的项目数量,如下所示:

project_id | created_by | created    | previous by created_by user    
    1      |     3      | 2015-04-01 |     0    
    2      |     3      | 2015-04-07 |     1    
    3      |     4      | 2015-05-01 |     0    
    4      |     4      | 2015-05-02 |     1

如何选择最后一列的计数?我已经尝试过count(情况,其中[condition]然后1 else null结束)但是当我使用它时我只得到一行结果。

3 个答案:

答案 0 :(得分:1)

您可以使用我在评论中提到过的子查询。

例如,查询可能如下所示:

SELECT t1.*, 
  (SELECT count(*) 
  FROM Table t2
  WHERE UNIX_TIMESTAMP(t2.date) < UNIX_TIMESTAMP( t1.date)
  AND t2.created_by = t1.created_by) before
 FROM Table t1

它将返回表格表格中的列。并将子查询的结果作为列&#39;之前的&#39;其中包含之前创建的行数。

答案 1 :(得分:0)

这就是你想要的吗?

select
project_id,
created_by,
created,
rn as `previous by created_by user`
from(
 select
 project_id,
 created_by,
 created,
 @rn:=if(@prev_created_by = created_by,@rn+1,0) as rn,
 @prev_created_by := created_by
 from project,(select @rn:=0,@prev_created_by:=null)x
 order by created_by,created
)x;

这是一个测试用例

mysql> select * from project ;
+------------+------------+------------+
| project_id | created_by | created    |
+------------+------------+------------+
|          1 |          3 | 2015-04-01 |
|          2 |          3 | 2015-04-07 |
|          3 |          4 | 2015-05-01 |
|          4 |          4 | 2015-05-02 |
+------------+------------+------------+
4 rows in set (0.00 sec)

以上查询将有

+------------+------------+------------+-----------------------------+
| project_id | created_by | created    | previous by created_by user |
+------------+------------+------------+-----------------------------+
|          1 |          3 | 2015-04-01 |                           0 |
|          2 |          3 | 2015-04-07 |                           1 |
|          3 |          4 | 2015-05-01 |                           0 |
|          4 |          4 | 2015-05-02 |                           1 |
+------------+------------+------------+-----------------------------+

答案 2 :(得分:0)

Select t1.project_id  , t1.created_by, t1.created,count(t2.created) 
from t1 , (select created_by,created from t1) as t2 
Where t1.created_by=t2.created_by and t1.created>t2.created     
group by t1.project_id  ,t1.created_by, t1.created