我想获得行数,但“计数”是一个特定情况。
id | category | time ============================================= 1 | 1 | 2015-02-09 12:00:00 2 | 3 | 2015-02-09 13:00:00 3 | 2 | 2015-02-09 14:00:00 4 | 3 | 2015-02-09 14:00:00 5 | 3 | 2015-02-09 15:00:00 6 | 1 | 2015-02-09 16:00:00 7 | 1 | 2015-02-09 16:00:00 8 | 1 | 2015-02-09 17:00:00
'计数'是相同的'类别'总数。
'为了'是“计数”的序数。按ASC排序
'为了'意思如下。
order | counts | id | category | time ======================================================== 1 | 4 | 1 | 1 | 2015-02-09 12:00:00 2 | 4 | 6 | 1 | 2015-02-09 16:00:00 3 | 4 | 7 | 1 | 2015-02-09 16:00:00 4 | 4 | 8 | 1 | 2015-02-09 17:00:00 1 | 1 | 3 | 2 | 2015-02-09 14:00:00 1 | 3 | 2 | 3 | 2015-02-09 13:00:00 2 | 3 | 4 | 3 | 2015-02-09 14:00:00 3 | 3 | 5 | 3 | 2015-02-09 15:00:00
如何编写查询以获得以下结果? (添加两列)
order | counts | id | category | time ======================================================== 1 | 4 | 1 | 1 | 2015-02-09 12:00:00 1 | 3 | 2 | 3 | 2015-02-09 13:00:00 1 | 1 | 3 | 2 | 2015-02-09 14:00:00 2 | 3 | 4 | 3 | 2015-02-09 14:00:00 3 | 3 | 5 | 3 | 2015-02-09 15:00:00 2 | 4 | 6 | 1 | 2015-02-09 16:00:00 3 | 4 | 7 | 1 | 2015-02-09 16:00:00 4 | 4 | 8 | 1 | 2015-02-09 17:00:00
答案 0 :(得分:1)
使用以下
Select id,category,(select count(*) from catt as ct where ct.category = catt.category)as counts from catt
工作DEMO
根据第二项要求 - >
set @category := '', @num := 1;
Select id,category,(select count(*) from catt as ct where ct.category =
catt.category)as counts,@num := if(@category = catt.category, @num + 1, 1) as
row_number , @category := category as dummy from catt order by category DESC
正在使用 SQLFiddle