mysql行数倒计时和动态行数

时间:2014-12-14 11:05:34

标签: mysql rows countdown

我相信它可以通过临时表/存储过程来解决,但是如果它可以通过单个SQL语句来完成。

目标:列出按年计算的所有行,但每年的行数不同。行可以按日期排序

结果武装到:

|-Count Down-|-Date-------|
| 3          | 2013-01-01 | <- Start with number of Row of each year
| 2          | 2013-03-15 |
| 1          | 2013-06-07 |
| 5          | 2014-01-01 | <- Start with number of Row of each year
| 4          | 2014-03-17 |
| 3          | 2014-07-11 |
| 2          | 2014-08-05 |
| 1          | 2014-11-12 |

SQL:

Select @row_number:=@row_number-1 AS CountDown, Date
FROM table JOIN 
    (Select @row_number:=COUNT(*), year(date) FROM table GROUP BY year(date))

有没有解决方案?

2 个答案:

答案 0 :(得分:0)

按年计算的子查询需要返回年份,因此您可以将其与主表连接以获取倒计时的起始编号。而且你需要检测年份的变化,所以你需要另一个变量。

SELECT @row_number := IF(YEAR(d.Date) = @prevYear, @row_number-1, y.c) AS CountDown,
       d.Date, @prevYear := YEAR(d.Date)
FROM (SELECT Date 
      FROM Table1 
      ORDER BY Date) AS d
JOIN 
    (Select count(*) AS c, year(date) AS year
     FROM Table1 
     GROUP BY year(date)) AS y
ON YEAR(d.Date) = y.year
CROSS JOIN (SELECT @prevYear := NULL) AS x

DEMO

答案 1 :(得分:0)

您可以使用变量(或相关子查询)进行倒计时。以下是计数,但返回的数据不是您指定的顺序:

select (@rn := if(@y = year(date), @rn + 1,
                  if(@y := year(date), 1, 1)
                 )
       ) as CountDown, t1.*
from table1 cross join
     (select @y := 0, @rn := 0) vars
order by date desc;

可以使用另一个子查询轻松修复:

select t.*
from (select (@rn := if(@y = year(date), @rn + 1,
                        if(@y := year(date), 1, 1)
                       )
             ) as CountDown, t1.*
      from table1 cross join
           (select @y := 0, @rn := 0) vars
      order by date desc
     ) t
order by date;

请注意分配CountDown的复杂表达式。此表达式将两个变量(@y@rn)设置在一个表达式中。 MySQL不保证select中表达式的评估顺序。如果您在不同的表达式中分配它们,那么它们可能会以错误的顺序执行。