如何查询和分组MySQL中的每个连续数字系列?

时间:2013-08-16 07:19:41

标签: mysql sqlyog

我有这个Freight.or_nos表,其中包含一系列收据编号。我想列出所有正在发布的,不包括状态='已取消',使系列分组。 例如,我有这张收据刺戳125001-125050,并且125020被取消,因此上市结果将是:

+-------------------------------------------------------+
|  OR Start  |    OR End    |   Quantity   |   Amount   |
+-------------------------------------------------------+
| 125001     | 125019       |           19 |            |
+-------------------------------------------------------+
| 125021     | 125050       |           30 |            |
+-------------------------------------------------------+

这似乎是一个棘手的问题。

1 个答案:

答案 0 :(得分:0)

感谢阅读,但我已经做到了,就在这! :) 这是我的查询(忽略它形成我们的CGI的其他字符):

{.while SELECT `start`,`end`,or_prefix,or_suffix,SUM(a.amount) AS g_total,COUNT(*) AS qcount FROM (SELECT l.id AS `start`,( SELECT MIN(a.id) AS id FROM ( SELECT a.or_no AS id FROM freight.`or_nos` a WHERE a.status!='Cancelled' AND a.log_user = 0@user_teller AND DATE(a.or_date)='@user_date`DATE'  AND IF(a.status='Default' AND a.amount=0,0,1)  ) AS a LEFT OUTER JOIN ( SELECT a.or_no AS id FROM freight.`or_nos` a WHERE a.status!='Cancelled' AND a.log_user = 0@user_teller AND DATE(a.or_date)='@user_date`DATE'  AND IF(a.status='Default' AND a.amount=0,0,1)    ) AS b ON a.id = b.id - 1 WHERE b.id IS NULL AND a.id >= l.id ) AS `end` FROM ( SELECT a.or_no AS id FROM freight.`or_nos` a WHERE a.status!='Cancelled' AND a.log_user = 0@user_teller AND DATE(a.or_date)='@user_date`DATE' AND IF(a.status='Default' AND a.amount=0,0,1)  ) AS l LEFT OUTER JOIN ( SELECT a.or_no AS id FROM freight.`or_nos` a WHERE a.log_user = 0@user_teller AND DATE(a.or_date)='@user_date`DATE' AND IF(a.status='Default' AND a.amount=0,0,1)  )  AS r ON r.id = l.id - 1 WHERE r.id IS NULL) AS k LEFT JOIN freight.`or_nos` a ON a.`or_no` BETWEEN k.start AND k.end  AND DATE(a.`or_date`)='@user_date`DATE' AND a.log_user =0@user_teller AND IF(a.status='Default' AND a.amount=0,0,1) AND a.status!='Cancelled' GROUP BY `start`}
          {.start}{.x.24.12:end}{.x`p0.40.-5:qcount}{.x`p2.57.-15:g_total}{.asc 255}
{.wend}{.asc 255}